Mercurial
comparison hg-web/e2e/app_e2e_test.js @ 231:09a96dcb2b4c hg-web
[merge] Join existing hg-web branch head
| author | MrJuneJune <me@mrjunejune.com> |
|---|---|
| date | Sun, 02 Aug 2026 16:50:48 -0700 |
| parents | 70de0c80d093 |
| children | c5129452493e |
comparison
equal
deleted
inserted
replaced
| 217:7ef4c9d2a72d | 231:09a96dcb2b4c |
|---|---|
| 1 const assert = require('node:assert/strict'); | |
| 2 const fs = require('node:fs'); | |
| 3 const os = require('node:os'); | |
| 4 const path = require('node:path'); | |
| 5 const { spawn, spawnSync } = require('node:child_process'); | |
| 6 const { chromium } = require('playwright-core'); | |
| 7 | |
| 8 const BASE_URL = 'http://127.0.0.1:6970'; | |
| 9 const RUNFILES = process.env.JS_BINARY__RUNFILES; | |
| 10 const WORKSPACE = process.env.JS_BINARY__WORKSPACE; | |
| 11 | |
| 12 function run(command, args, options = {}) { | |
| 13 const result = spawnSync(command, args, { | |
| 14 encoding: 'utf8', | |
| 15 ...options, | |
| 16 }); | |
| 17 if (result.status !== 0) { | |
| 18 throw new Error( | |
| 19 `${command} ${args.join(' ')} failed\n${result.stdout || ''}${result.stderr || ''}`, | |
| 20 ); | |
| 21 } | |
| 22 return result.stdout.trim(); | |
| 23 } | |
| 24 | |
| 25 function mercurialEnvironment(home) { | |
| 26 return { | |
| 27 ...process.env, | |
| 28 HGPLAIN: '1', | |
| 29 HGRCPATH: '', | |
| 30 HOME: home, | |
| 31 }; | |
| 32 } | |
| 33 | |
| 34 function stopProcess(child) { | |
| 35 if (!child || child.exitCode !== null) return Promise.resolve(); | |
| 36 child.kill('SIGTERM'); | |
| 37 return new Promise(resolve => { | |
| 38 const timer = setTimeout(() => { | |
| 39 if (child.exitCode === null) child.kill('SIGKILL'); | |
| 40 }, 3000); | |
| 41 child.once('exit', () => { | |
| 42 clearTimeout(timer); | |
| 43 resolve(); | |
| 44 }); | |
| 45 }); | |
| 46 } | |
| 47 | |
| 48 async function waitForHttp(url, child, logs) { | |
| 49 const deadline = Date.now() + 15000; | |
| 50 while (Date.now() < deadline) { | |
| 51 if (child.exitCode !== null) { | |
| 52 throw new Error(`Server exited early with ${child.exitCode}\n${logs.join('')}`); | |
| 53 } | |
| 54 try { | |
| 55 const response = await fetch(url); | |
| 56 if (response.ok) return; | |
| 57 } catch { | |
| 58 // Keep waiting for startup. | |
| 59 } | |
| 60 await new Promise(resolve => setTimeout(resolve, 100)); | |
| 61 } | |
| 62 throw new Error(`Timed out waiting for ${url}\n${logs.join('')}`); | |
| 63 } | |
| 64 | |
| 65 function createFixtureRepository(root) { | |
| 66 const options = { env: mercurialEnvironment(root) }; | |
| 67 run('hg', ['init', root], options); | |
| 68 fs.mkdirSync(path.join(root, 'docs'), { recursive: true }); | |
| 69 fs.mkdirSync(path.join(root, 'src'), { recursive: true }); | |
| 70 fs.writeFileSync( | |
| 71 path.join(root, 'README.md'), | |
| 72 '# Fixture Repository\n\n<script>window.__hgWebXss = true</script>\n', | |
| 73 ); | |
| 74 fs.writeFileSync(path.join(root, 'docs', 'README.md'), '# Documentation\n\nNested README.\n'); | |
| 75 fs.writeFileSync(path.join(root, 'src', 'main.c'), 'int main(void) { return 0; }\n'); | |
| 76 fs.writeFileSync( | |
| 77 path.join(root, 'BUILD'), | |
| 78 'cc_library(\n name = "fixture",\n srcs = ["src/main.c"],\n)\n', | |
| 79 ); | |
| 80 fs.writeFileSync( | |
| 81 path.join(root, 'pixel.png'), | |
| 82 Buffer.from( | |
| 83 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl2nWQAAAAASUVORK5CYII=', | |
| 84 'base64', | |
| 85 ), | |
| 86 ); | |
| 87 fs.writeFileSync(path.join(root, 'movie.mp4'), Buffer.from('00000018667479706d703432', 'hex')); | |
| 88 fs.writeFileSync(path.join(root, 'sound.mp3'), Buffer.from('ID3')); | |
| 89 fs.writeFileSync(path.join(root, 'document.pdf'), Buffer.from('%PDF-1.4\n%%EOF\n')); | |
| 90 fs.writeFileSync(path.join(root, 'archive.bin'), Buffer.from([0, 1, 2, 3])); | |
| 91 run('hg', ['--repository', root, 'add'], options); | |
| 92 run('hg', ['--repository', root, 'commit', '-u', 'Test User <[email protected]>', '-m', 'Initial fixture'], options); | |
| 93 const firstNode = run('hg', ['--repository', root, 'log', '-r', '.', '-T', '{node}'], options); | |
| 94 | |
| 95 fs.writeFileSync( | |
| 96 path.join(root, 'README.md'), | |
| 97 '# Updated Fixture Repository\n\n<script>window.__hgWebXss = true</script>\n\nSecond revision.\n', | |
| 98 ); | |
| 99 fs.writeFileSync(path.join(root, 'new-file.txt'), 'new file\n'); | |
| 100 run('hg', ['add', 'new-file.txt'], { ...options, cwd: root }); | |
| 101 run('hg', ['--repository', root, 'commit', '-u', 'Test User <[email protected]>', '-m', 'Update fixture'], options); | |
| 102 const tipNode = run('hg', ['--repository', root, 'log', '-r', '.', '-T', '{node}'], options); | |
| 103 return { firstNode, tipNode }; | |
| 104 } | |
| 105 | |
| 106 async function assertJson(pathname, status = 200) { | |
| 107 const response = await fetch(`${BASE_URL}${pathname}`); | |
| 108 const body = await response.text(); | |
| 109 assert.equal(response.status, status, `${pathname} status: ${body}`); | |
| 110 return JSON.parse(body); | |
| 111 } | |
| 112 | |
| 113 async function assertPageHasNoBrowserErrors(browser, pathname, assertion) { | |
| 114 const page = await browser.newPage(); | |
| 115 const errors = []; | |
| 116 page.on('pageerror', error => errors.push(`pageerror: ${error.stack || error.message}`)); | |
| 117 page.on('console', message => { | |
| 118 if (message.type() === 'error') errors.push(`console: ${message.text()}`); | |
| 119 }); | |
| 120 page.on('requestfailed', request => { | |
| 121 errors.push(`requestfailed: ${request.url()} ${request.failure()?.errorText || ''}`); | |
| 122 }); | |
| 123 page.on('response', response => { | |
| 124 if (response.status() >= 400) { | |
| 125 errors.push(`response: ${response.status()} ${response.url()}`); | |
| 126 } | |
| 127 }); | |
| 128 | |
| 129 const response = await page.goto(`${BASE_URL}${pathname}`, { waitUntil: 'networkidle' }); | |
| 130 assert.equal(response.status(), 200, `${pathname} document status`); | |
| 131 await assertion(page); | |
| 132 if (errors.length > 0) { | |
| 133 throw new Error(`${pathname} browser errors\n${errors.join('\n')}`); | |
| 134 } | |
| 135 await page.close(); | |
| 136 } | |
| 137 | |
| 138 async function main() { | |
| 139 assert.ok(RUNFILES, 'rules_js runfiles path is required'); | |
| 140 assert.ok(WORKSPACE, 'rules_js workspace name is required'); | |
| 141 | |
| 142 const fixtureRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'hg-web-e2e-')); | |
| 143 const appLogs = []; | |
| 144 const hgLogs = []; | |
| 145 let hgServer; | |
| 146 let appServer; | |
| 147 let browser; | |
| 148 | |
| 149 try { | |
| 150 const { firstNode, tipNode } = createFixtureRepository(fixtureRoot); | |
| 151 const runfilesWorkspace = path.join(RUNFILES, WORKSPACE); | |
| 152 const serverBinary = path.join(runfilesWorkspace, 'hg-web', 'hg_web_server'); | |
| 153 const chromiumPath = path.resolve(process.env.CHROMIUM_PATH); | |
| 154 | |
| 155 assert.ok(fs.existsSync(serverBinary), `missing server binary: ${serverBinary}`); | |
| 156 assert.ok(fs.existsSync(chromiumPath), `missing Chromium binary: ${chromiumPath}`); | |
| 157 | |
| 158 hgServer = spawn( | |
| 159 'hg', | |
| 160 [ | |
| 161 '--repository', fixtureRoot, | |
| 162 'serve', | |
| 163 '--address', '127.0.0.1', | |
| 164 '--port', '4444', | |
| 165 '--accesslog', '-', | |
| 166 '--errorlog', '-', | |
| 167 ], | |
| 168 { | |
| 169 env: mercurialEnvironment(fixtureRoot), | |
| 170 stdio: ['ignore', 'pipe', 'pipe'], | |
| 171 }, | |
| 172 ); | |
| 173 hgServer.stdout.on('data', chunk => hgLogs.push(chunk.toString())); | |
| 174 hgServer.stderr.on('data', chunk => hgLogs.push(chunk.toString())); | |
| 175 | |
| 176 appServer = spawn(serverBinary, [], { | |
| 177 cwd: runfilesWorkspace, | |
| 178 stdio: ['ignore', 'pipe', 'pipe'], | |
| 179 }); | |
| 180 appServer.stdout.on('data', chunk => appLogs.push(chunk.toString())); | |
| 181 appServer.stderr.on('data', chunk => appLogs.push(chunk.toString())); | |
| 182 | |
| 183 await waitForHttp(`${BASE_URL}/`, appServer, appLogs); | |
| 184 if (hgServer.exitCode !== null) { | |
| 185 throw new Error(`Mercurial server exited early with ${hgServer.exitCode}\n${hgLogs.join('')}`); | |
| 186 } | |
| 187 await waitForHttp(`${BASE_URL}/api/repo/list`, hgServer, hgLogs); | |
| 188 | |
| 189 for (const pathname of ['/', '/directory', '/directory?path=docs', '/graph', `/changeset/${tipNode}`]) { | |
| 190 const response = await fetch(`${BASE_URL}${pathname}`); | |
| 191 assert.equal(response.status, 200, `${pathname} shell route`); | |
| 192 assert.match(await response.text(), /<title>Zenbu Repository<\/title>/); | |
| 193 } | |
| 194 for (const pathname of ['/page.js', '/index.css', '/base.css', '/pencil_lines.png', '/panda.png']) { | |
| 195 const response = await fetch(`${BASE_URL}${pathname}`); | |
| 196 assert.equal(response.status, 200, `${pathname} static asset`); | |
| 197 assert.ok((await response.arrayBuffer()).byteLength > 0, `${pathname} is non-empty`); | |
| 198 } | |
| 199 for (const pathname of ['/hg-web-background.jpg', '/pencil_texture.png']) { | |
| 200 assert.equal((await fetch(`${BASE_URL}${pathname}`)).status, 404); | |
| 201 } | |
| 202 | |
| 203 const rootList = await assertJson('/api/repo/list'); | |
| 204 assert.ok(rootList.directories.some(entry => entry.basename === 'docs')); | |
| 205 assert.ok(rootList.files.some(entry => entry.basename === 'README.md')); | |
| 206 | |
| 207 const nestedList = await assertJson('/api/repo/list?path=docs'); | |
| 208 assert.ok(nestedList.files.some(entry => entry.basename === 'README.md')); | |
| 209 | |
| 210 const fileResponse = await fetch(`${BASE_URL}/api/repo/file?path=src%2Fmain.c`); | |
| 211 assert.equal(fileResponse.status, 200); | |
| 212 assert.match(await fileResponse.text(), /int main/); | |
| 213 | |
| 214 for (const [filename, contentType, disposition] of [ | |
| 215 ['pixel.png', 'image/png', 'inline'], | |
| 216 ['movie.mp4', 'video/mp4', 'inline'], | |
| 217 ['sound.mp3', 'audio/mpeg', 'inline'], | |
| 218 ['document.pdf', 'application/pdf', 'inline'], | |
| 219 ['archive.bin', 'application/octet-stream', 'attachment'], | |
| 220 ]) { | |
| 221 const response = await fetch( | |
| 222 `${BASE_URL}/api/repo/file?path=${encodeURIComponent(filename)}`, | |
| 223 ); | |
| 224 assert.equal(response.status, 200, `${filename} response`); | |
| 225 assert.match(response.headers.get('content-type') || '', new RegExp(`^${contentType}`)); | |
| 226 assert.equal(response.headers.get('content-disposition'), disposition); | |
| 227 assert.equal(response.headers.get('x-content-type-options'), 'nosniff'); | |
| 228 assert.ok((await response.arrayBuffer()).byteLength > 0); | |
| 229 } | |
| 230 const binaryResponse = await fetch(`${BASE_URL}/api/repo/file?path=archive.bin`); | |
| 231 assert.deepEqual( | |
| 232 Buffer.from(await binaryResponse.arrayBuffer()), | |
| 233 Buffer.from([0, 1, 2, 3]), | |
| 234 ); | |
| 235 | |
| 236 const readmeResponse = await fetch(`${BASE_URL}/api/repo/readme?path=docs`); | |
| 237 assert.equal(readmeResponse.status, 200); | |
| 238 assert.match(await readmeResponse.text(), /Nested README/); | |
| 239 assert.equal((await fetch(`${BASE_URL}/api/repo/readme?path=src`)).status, 204); | |
| 240 | |
| 241 const graph = await assertJson('/api/graph/tip?style=json'); | |
| 242 assert.equal(graph.node, tipNode); | |
| 243 assert.ok(graph.changesets.length >= 2); | |
| 244 | |
| 245 const changeset = await assertJson(`/api/changeset/${tipNode}`); | |
| 246 assert.equal(changeset.node, tipNode); | |
| 247 assert.equal(changeset.desc, 'Update fixture'); | |
| 248 assert.ok(changeset.files.some(entry => entry.file === 'new-file.txt' && entry.status === 'added')); | |
| 249 assert.ok(changeset.diff.length > 0); | |
| 250 | |
| 251 for (const pathname of [ | |
| 252 '/api/repo/list?path=..%2Fetc', | |
| 253 '/api/repo/file?path=..%2FREADME.md', | |
| 254 '/api/graph/not-a-node?style=json', | |
| 255 '/api/changeset/not-a-node', | |
| 256 ]) { | |
| 257 const response = await fetch(`${BASE_URL}${pathname}`); | |
| 258 assert.equal(response.status, 400, `${pathname} rejects invalid input`); | |
| 259 } | |
| 260 assert.equal((await fetch(`${BASE_URL}/missing-route`)).status, 404); | |
| 261 | |
| 262 const identify = run( | |
| 263 'hg', | |
| 264 ['identify', `${BASE_URL}/repo`], | |
| 265 { env: mercurialEnvironment(fixtureRoot) }, | |
| 266 ); | |
| 267 assert.match(identify, new RegExp(`^${tipNode.slice(0, 12)}`)); | |
| 268 | |
| 269 browser = await chromium.launch({ | |
| 270 executablePath: chromiumPath, | |
| 271 headless: true, | |
| 272 args: ['--no-sandbox'], | |
| 273 }); | |
| 274 | |
| 275 await assertPageHasNoBrowserErrors(browser, '/', async page => { | |
| 276 await page.getByRole('heading', { name: 'Zenbu Repository' }).waitFor(); | |
| 277 await page.getByText('Recent Commits').waitFor(); | |
| 278 await page.getByText('Repository Files').waitFor(); | |
| 279 assert.equal(await page.evaluate(() => window.__hgWebXss), undefined); | |
| 280 assert.equal( | |
| 281 await page.locator('.graph-container').evaluate( | |
| 282 element => getComputedStyle(element).backgroundImage, | |
| 283 ), | |
| 284 'none', | |
| 285 ); | |
| 286 await page.locator('.theme-toggle').click(); | |
| 287 }); | |
| 288 | |
| 289 await assertPageHasNoBrowserErrors(browser, '/directory', async page => { | |
| 290 await page.getByText('Repository Files').waitFor(); | |
| 291 await page.getByRole('link', { name: 'README.md' }).first().click(); | |
| 292 await page.getByText('Updated Fixture Repository').waitFor(); | |
| 293 assert.equal(await page.evaluate(() => window.__hgWebXss), undefined); | |
| 294 await page.keyboard.press('Escape'); | |
| 295 | |
| 296 let delayedReadmeRequested = false; | |
| 297 let markReadmeRequested; | |
| 298 const readmeRequested = new Promise(resolve => { | |
| 299 markReadmeRequested = resolve; | |
| 300 }); | |
| 301 await page.route(/\/api\/repo\/readme\?path=/, async route => { | |
| 302 delayedReadmeRequested = true; | |
| 303 markReadmeRequested(); | |
| 304 await new Promise(resolve => setTimeout(resolve, 500)); | |
| 305 await route.continue(); | |
| 306 }); | |
| 307 await page.getByRole('link', { name: 'docs' }).click(); | |
| 308 await Promise.race([ | |
| 309 readmeRequested, | |
| 310 new Promise((_, reject) => { | |
| 311 setTimeout(() => reject(new Error('Timed out waiting for delayed README request')), 5000); | |
| 312 }), | |
| 313 ]); | |
| 314 await page.getByRole('link', { name: 'root' }).click(); | |
| 315 await page.getByText('Updated Fixture Repository').waitFor(); | |
| 316 await page.waitForTimeout(600); | |
| 317 assert.equal(await page.getByText('Documentation').count(), 0); | |
| 318 assert.equal(delayedReadmeRequested, true); | |
| 319 | |
| 320 await page.getByRole('link', { name: 'pixel.png' }).click(); | |
| 321 const image = page.locator('.static-file-image'); | |
| 322 await image.waitFor(); | |
| 323 await image.evaluate(element => { | |
| 324 const imageElement = element; | |
| 325 if (imageElement.complete) return; | |
| 326 return new Promise((resolve, reject) => { | |
| 327 imageElement.addEventListener('load', resolve, { once: true }); | |
| 328 imageElement.addEventListener('error', reject, { once: true }); | |
| 329 }); | |
| 330 }); | |
| 331 assert.equal(await image.evaluate(element => element.naturalWidth), 1); | |
| 332 await page.getByRole('dialog', { name: 'Preview pixel.png' }).waitFor(); | |
| 333 await page.keyboard.press('Escape'); | |
| 334 | |
| 335 await page.getByRole('link', { name: 'BUILD' }).click(); | |
| 336 const buildCode = page.locator('code.language-python'); | |
| 337 await buildCode.waitFor(); | |
| 338 await page.getByText('cc_library').waitFor(); | |
| 339 assert.match(await buildCode.textContent(), /name = "fixture"/); | |
| 340 await page.keyboard.press('Escape'); | |
| 341 | |
| 342 await page.getByRole('link', { name: 'src' }).click(); | |
| 343 await page.getByRole('link', { name: 'main.c' }).click(); | |
| 344 await page.getByText('int main(void)').waitFor(); | |
| 345 await page.keyboard.press('Escape'); | |
| 346 }); | |
| 347 | |
| 348 await assertPageHasNoBrowserErrors(browser, '/directory?path=docs', async page => { | |
| 349 await page.getByText('Documentation').waitFor(); | |
| 350 await page.getByRole('link', { name: 'README.md' }).click(); | |
| 351 await page.getByText('Nested README.').waitFor(); | |
| 352 }); | |
| 353 | |
| 354 await assertPageHasNoBrowserErrors(browser, '/graph', async page => { | |
| 355 await page.getByText('Commit Graph').waitFor(); | |
| 356 await page.waitForFunction(() => new URL(window.location.href).searchParams.has('tip')); | |
| 357 const graphUrl = page.url(); | |
| 358 const rows = page.locator('.graph-row'); | |
| 359 await rows.first().click(); | |
| 360 await page.waitForURL(/\/changeset\/[0-9a-f]+$/); | |
| 361 await page.getByRole('heading', { name: 'Update fixture' }).waitFor(); | |
| 362 await page.getByRole('button', { name: 'Back', exact: true }).click(); | |
| 363 await page.waitForFunction(expected => window.location.href === expected, graphUrl); | |
| 364 await page.getByText('Commit Graph').waitFor(); | |
| 365 }); | |
| 366 | |
| 367 await assertPageHasNoBrowserErrors(browser, `/changeset/${tipNode}`, async page => { | |
| 368 await page.getByRole('heading', { name: 'Update fixture' }).waitFor(); | |
| 369 await page.locator('.changeset-files code').filter({ hasText: 'new-file.txt' }).waitFor(); | |
| 370 await page.getByText('added', { exact: true }).waitFor(); | |
| 371 await page.getByRole('region', { name: 'Changeset diff' }).waitFor(); | |
| 372 await page.locator('.diff-column-headings').getByText('Before').first().waitFor(); | |
| 373 await page.locator('.diff-column-headings').getByText('After').first().waitFor(); | |
| 374 await page.locator('.diff-left.diff-remove').filter({ hasText: '# Fixture Repository' }).waitFor(); | |
| 375 await page.locator('.diff-right.diff-add').filter({ hasText: '# Updated Fixture Repository' }).waitFor(); | |
| 376 assert.equal( | |
| 377 await page.locator('.diff-left.diff-context').filter({ hasText: '<script>' }).first().textContent(), | |
| 378 '<script>window.__hgWebXss = true</script>', | |
| 379 ); | |
| 380 assert.equal( | |
| 381 await page.locator('.changeset-paper').evaluate( | |
| 382 element => getComputedStyle(element).backgroundImage, | |
| 383 ), | |
| 384 'none', | |
| 385 ); | |
| 386 await page.getByRole('button', { name: firstNode.slice(0, 12) }).click(); | |
| 387 await page.waitForFunction( | |
| 388 expectedPath => window.location.pathname === expectedPath, | |
| 389 `/changeset/${firstNode}`, | |
| 390 ); | |
| 391 await page.getByRole('heading', { name: 'Initial fixture' }).waitFor(); | |
| 392 await page.getByRole('button', { name: 'Back', exact: true }).click(); | |
| 393 await page.getByRole('heading', { name: 'Update fixture' }).waitFor(); | |
| 394 await page.getByRole('button', { name: 'Back', exact: true }).click(); | |
| 395 await page.getByText('Commit Graph').waitFor(); | |
| 396 }); | |
| 397 | |
| 398 await assertPageHasNoBrowserErrors(browser, '/changeset/not-a-node', async page => { | |
| 399 await page.getByText('Recent Commits').waitFor(); | |
| 400 }); | |
| 401 | |
| 402 await stopProcess(hgServer); | |
| 403 const unavailable = await fetch(`${BASE_URL}/api/repo/list`); | |
| 404 assert.equal(unavailable.status, 502); | |
| 405 assert.equal((await fetch(`${BASE_URL}/`)).status, 200); | |
| 406 } finally { | |
| 407 if (browser) await browser.close(); | |
| 408 await stopProcess(appServer); | |
| 409 await stopProcess(hgServer); | |
| 410 fs.rmSync(fixtureRoot, { recursive: true, force: true }); | |
| 411 } | |
| 412 } | |
| 413 | |
| 414 main().catch(error => { | |
| 415 console.error(error.stack || error); | |
| 416 process.exitCode = 1; | |
| 417 }); |