diff --git a/apps/web/check/app.mjs b/apps/web/check/app.mjs index 581c69a..57207ab 100644 --- a/apps/web/check/app.mjs +++ b/apps/web/check/app.mjs @@ -1,94 +1,67 @@ -// The web version in headless Firefox: the page for phones, the program, opening a PGN -// by its button (Ctrl+O) and by dropping it, a game from the classics, moves, a -// download of the PGN. Screenshots go to ; what is checked is printed. +// The web version in a headless browser (Firefox; Chromium with CP_BROWSER=chromium): +// the page for phones, the program, opening a PGN by its button (Ctrl+O) and by +// dropping it, a game from the classics, moves, a download of the PGN, a move on the +// board, the browser's Back. Screenshots go to ; what is checked is printed. // // node apps/web/check/app.mjs (app-dir: apps/web/build.sh's) -import { spawn } from 'node:child_process'; import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; import { join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; -import { launch } from './firefox.mjs'; -import { sleep, tab } from './bidi.mjs'; +import { session } from './steps.mjs'; +import { sleep } from './bidi.mjs'; const [appDir, outDir] = process.argv.slice(2).map((p) => resolve(p)); const root = fileURLToPath(new URL('../../..', import.meta.url)); mkdirSync(outDir, { recursive: true }); -const port = 18766; -const server = spawn('python3', ['-I', join(root, 'apps/web/check/serve.py'), appDir, join(root, 'website/static'), String(port)], { stdio: 'ignore' }); -const base = `http://127.0.0.1:${port}/app/`; - let failures = 0; const check = (ok, what) => { console.log(`${ok ? 'ok ' : 'FAIL'} ${what}`); if (!ok) failures++; }; -const errors = []; -const log = (line) => { - if (/panicked|RuntimeError|did not start|\[error\]/.test(line)) errors.push(line); -}; - -const ff = await launch(19223); -const shot = async (t, name) => writeFileSync(join(outDir, name), await t.screenshot()); -const key = (value, mods = []) => { - const down = mods.map((m) => ({ type: 'keyDown', value: m })); - const up = mods.map((m) => ({ type: 'keyUp', value: m })).reverse(); - return [...down, { type: 'keyDown', value }, { type: 'keyUp', value }, ...up, { type: 'pause', duration: 80 }]; -}; -const CTRL = ''; -const RIGHT = ''; -const click = (x, y, count = 1) => { - const acts = [{ type: 'pointerMove', x, y }]; - for (let i = 0; i < count; i++) acts.push({ type: 'pointerDown', button: 0 }, { type: 'pointerUp', button: 0 }); - return [{ type: 'pointer', id: 'mouse', parameters: { pointerType: 'mouse' }, actions: acts }]; -}; -const started = (t) => t.waitFor(`document.getElementById('cp-status').hidden && !document.getElementById('cp-app').hidden`, 30000); +// Places of buttons in a 1400×860 window. +const DOWNLOAD = [Number(process.env.DOWNLOAD_X || 1263), Number(process.env.DOWNLOAD_Y || 24)]; +const E2 = [519, 703]; +const E4 = [519, 505]; +const s = await session(appDir, 18766); +const { t } = s; +const shot = async (name) => writeFileSync(join(outDir, name), await t.screenshot()); +const text = () => t.evaluate(`document.getElementById('cp-device').innerText`); +const started = () => t.waitFor(`document.getElementById('cp-status').hidden && !document.getElementById('cp-app').hidden`, 30000); try { - // ----- the page for phones and tablets, without the program ------------------------------ - { - const t = await tab(ff.browser, 390, 844, log); - await t.navigate(`${base}?phone=1&lang=ru`); - await sleep(800); - const text = await t.evaluate(`document.getElementById('cp-device').innerText`); - check(/ChessPenguin на телефоне и планшете/.test(text), 'the device page in Russian'); - check(/Всё равно открыть веб-версию/.test(text), 'with «open the web version anyway»'); - const wasm = await t.evaluate(`performance.getEntriesByType('resource').some(e => e.name.endsWith('.wasm'))`); - check(!wasm, 'the program is not downloaded on it'); - await shot(t, 'web-phone-ru.png'); - await t.navigate(`${base}?phone=1&lang=de`); - await sleep(500); - check(/auf Handy und Tablet/.test(await t.evaluate(`document.getElementById('cp-device').innerText`)), 'the device page in German'); - await t.navigate(`${base}?phone=android&lang=ru`); - await sleep(800); - check(/Скачать для Android/.test(await t.evaluate(`document.getElementById('cp-device').innerText`)), 'the Android variant'); - await shot(t, 'web-phone-android-ru.png'); - await t.navigate(`${base}?phone=ios&lang=en`); - await sleep(800); - check(/iPhone and iPad app is coming soon/.test(await t.evaluate(`document.getElementById('cp-device').innerText`)), 'the iPhone and iPad variant'); - await shot(t, 'web-phone-ios-en.png'); - } + // ----- the page for phones and tablets, without the program ---------------------------- + await t.navigate(`${s.base}?phone=1&lang=ru`); + await sleep(800); + check(/ChessPenguin на телефоне и планшете/.test(await text()), 'the device page in Russian'); + check(/Всё равно открыть веб-версию/.test(await text()), 'with «open the web version anyway»'); + const wasm = await t.evaluate(`performance.getEntriesByType('resource').some(e => e.name.endsWith('.wasm'))`); + check(!wasm, 'the program is not downloaded on it'); + await shot('web-phone-ru.png'); + await t.navigate(`${s.base}?phone=1&lang=de`); + await sleep(500); + check(/auf Handy und Tablet/.test(await text()), 'the device page in German'); + await t.navigate(`${s.base}?phone=android&lang=ru`); + await sleep(800); + check(/Скачать для Android/.test(await text()), 'the Android variant'); + await t.navigate(`${s.base}?phone=ios&lang=en`); + await sleep(800); + check(/iPhone and iPad app is coming soon/.test(await text()), 'the iPhone and iPad variant'); // ----- the program ------------------------------------------------------------------------- - const t = await tab(ff.browser, 1400, 860, log); - await t.navigate(`${base}?lang=en`); - await started(t); + await t.navigate(`${s.base}?lang=en`); + await started(); await sleep(2500); - check(true, 'the program started (WebGL canvas, no error)'); - await shot(t, 'web-1-library.png'); + check(true, `the program started in ${s.b.name}`); + await shot('web-1-library.png'); // Open a PGN by the button's shortcut: the browser's file chooser gets the file. - const pgn = join(ff.profile, 'Test games.pgn'); + const pgn = join(s.b.profile, 'Test games.pgn'); copyFileSync(join(root, 'examples/alekhine.pgn'), pgn); - await t.actions([{ type: 'key', id: 'kb', actions: key('o', [CTRL]) }]); + await t.key('o', ['ctrl']); await t.waitFor(`!!document.getElementById('cp-open-files')`, 5000); - const input = await ff.browser.send('script.evaluate', { - expression: `document.getElementById('cp-open-files')`, - target: { context: t.context }, - awaitPromise: false, - }); - await ff.browser.send('input.setFiles', { context: t.context, element: { sharedId: input.result.sharedId }, files: [pgn] }); - await sleep(2500); - await shot(t, 'web-2-opened.png'); + await t.setFiles('cp-open-files', [pgn]); + await sleep(3000); + await shot('web-2-opened.png'); // Drop a file on the window. const dropped = readFileSync(join(root, 'examples/classics.pgn'), 'utf8'); @@ -100,61 +73,51 @@ try { c.dispatchEvent(new DragEvent(type, { dataTransfer: dt, bubbles: true, cancelable: true, clientX: 700, clientY: 400 })); return true; })()`); - await sleep(2500); - await shot(t, 'web-3-dropped.png'); + await sleep(3000); + await shot('web-3-dropped.png'); - // The classics: a game opens from the table (double click), its moves on the board. - await t.actions(click(Number(process.env.CLASSICS_X || 100), Number(process.env.CLASSICS_Y || 70))); + // A game from the table (double click), its moves on the board. + await t.click(300, 322, { double: true }); await sleep(1500); - await t.actions(click(300, Number(process.env.ROW_Y || 322), 2)); - await sleep(1500); - await shot(t, 'web-4-game.png'); - const steps = []; - for (let i = 0; i < 12; i++) steps.push(...key(RIGHT)); - await t.actions([{ type: 'key', id: 'kb', actions: steps }]); + await shot('web-4-game.png'); + await t.key('right', [], 12); await sleep(800); - await shot(t, 'web-5-moves.png'); + await shot('web-5-moves.png'); // Download the PGN of the game (the header's button). - await t.actions(click(Number(process.env.DOWNLOAD_X || 1180), Number(process.env.DOWNLOAD_Y || 22))); - await sleep(2000); - const files = existsSync(ff.downloads) ? readdirSync(ff.downloads).filter((f) => f.endsWith('.pgn')) : []; + await t.click(...DOWNLOAD); + await sleep(2500); + const files = existsSync(s.b.downloads) ? readdirSync(s.b.downloads).filter((f) => f.endsWith('.pgn')) : []; check(files.length === 1, `a PGN downloaded: ${files.join(', ') || 'none'}`); if (files.length) { - const text = readFileSync(join(ff.downloads, files[0]), 'utf8'); - check(/\[White "/.test(text) && /1\. /.test(text), 'the download is the game in PGN'); - writeFileSync(join(outDir, 'web-download.pgn'), text); + const body = readFileSync(join(s.b.downloads, files[0]), 'utf8'); + check(/\[White "/.test(body) && /1\. /.test(body), 'the download is the game in PGN'); } - await shot(t, 'web-6-downloaded.png'); - // A move on the board of a new game (Ctrl+N): e2–e4 by two clicks. - await t.actions([{ type: 'key', id: 'kb', actions: key('') }]); - await sleep(500); - await t.actions([{ type: 'key', id: 'kb', actions: key('') }]); - await sleep(800); - await t.actions([{ type: 'key', id: 'kb', actions: key('n', [CTRL]) }]); + // The browser's Back is «← Library». + await t.evaluate(`history.back()`); + await sleep(1500); + await shot('web-6-back.png'); + check(await t.evaluate(`history.state === null || !history.state.cpGame`), 'Back left the game for the library'); + + // A move on the board of a new game (Ctrl+N; N in a browser): e2–e4 by two clicks. + await t.key('n'); await sleep(1200); - await shot(t, 'web-7-new-game.png'); - if (process.env.E2 && process.env.E4) { - const [x2, y2] = process.env.E2.split(',').map(Number); - const [x4, y4] = process.env.E4.split(',').map(Number); - await t.actions(click(x2, y2)); - await sleep(300); - await t.actions(click(x4, y4)); - await sleep(1000); - await shot(t, 'web-8-e4.png'); - } + await t.click(...E2); + await sleep(300); + await t.click(...E4); + await sleep(1000); + await shot('web-8-e4.png'); - // The settings and the marks survive a reload (the browser's storage). - await t.navigate(`${base}?lang=en`); - await started(t); + // The settings and the shelf after a reload (the browser's storage). + await t.navigate(`${s.base}?lang=en`); + await started(); await sleep(2500); - await shot(t, 'web-9-reloaded.png'); + await shot('web-9-reloaded.png'); } finally { - await ff.stop(); - server.kill(); + await s.stop(); } -for (const e of errors) console.log('console:', e); -check(errors.length === 0, 'no panic or error in the console'); +for (const e of s.errors) console.log('console:', e); +check(s.errors.length === 0, 'no panic or error in the console'); console.log(failures ? `${failures} failed` : 'all ok'); process.exit(failures ? 1 : 0); diff --git a/apps/web/check/browser.mjs b/apps/web/check/browser.mjs new file mode 100644 index 0000000..0f0bf07 --- /dev/null +++ b/apps/web/check/browser.mjs @@ -0,0 +1,217 @@ +// One way to drive a headless browser for the web checks: Firefox over WebDriver BiDi +// (firefox.mjs, bidi.mjs) or Chromium / Chrome for Testing over the DevTools protocol. +// The browser: CP_BROWSER=firefox (default) | chromium, the Chromium binary in +// CP_CHROME. No window is ever shown; the browser is stopped by its PID. +// +// const b = await open(port); const t = await b.tab(1400, 860, log); +// t.navigate(url) · t.evaluate(js) · t.waitFor(js, ms) · t.screenshot() +// t.click(x, y, {double, right}) · t.key(key, mods, times) · t.setFiles(inputId, paths) +import { spawn } from 'node:child_process'; +import { mkdirSync, mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { launch as launchFirefox } from './firefox.mjs'; +import { sleep, tab as bidiTab } from './bidi.mjs'; + +// WebDriver key values (BiDi) and their DevTools descriptions. +const KEYS = { + ctrl: { bidi: '', key: 'Control', code: 'ControlLeft', vk: 17, mod: 2 }, + shift: { bidi: '', key: 'Shift', code: 'ShiftLeft', vk: 16, mod: 8 }, + alt: { bidi: '', key: 'Alt', code: 'AltLeft', vk: 18, mod: 1 }, + esc: { bidi: '', key: 'Escape', code: 'Escape', vk: 27 }, + enter: { bidi: '', key: 'Enter', code: 'Enter', vk: 13, text: '\r' }, + right: { bidi: '', key: 'ArrowRight', code: 'ArrowRight', vk: 39 }, + left: { bidi: '', key: 'ArrowLeft', code: 'ArrowLeft', vk: 37 }, +}; + +function keyOf(k) { + if (KEYS[k]) return KEYS[k]; + if (k === ',') return { bidi: ',', key: ',', code: 'Comma', vk: 188, text: ',' }; + if (/^[0-9]$/.test(k)) return { bidi: k, key: k, code: `Digit${k}`, vk: 48 + Number(k), text: k }; + return { bidi: k, key: k, code: `Key${k.toUpperCase()}`, vk: k.toUpperCase().charCodeAt(0), text: k }; +} + +const waitFor = (evaluate) => async (expression, ms = 10000) => { + const end = Date.now() + ms; + for (;;) { + const v = await evaluate(expression).catch(() => undefined); + if (v) return v; + if (Date.now() > end) throw new Error(`timed out waiting for ${expression}`); + await sleep(100); + } +}; + +// ----- Firefox -------------------------------------------------------------------------- + +async function firefox(port) { + const ff = await launchFirefox(port); + return { + name: 'firefox', + profile: ff.profile, + downloads: ff.downloads, + stop: ff.stop, + tab: async (width, height, log) => { + const t = await bidiTab(ff.browser, width, height, log); + const evaluate = async (expression) => { + const r = await ff.browser.send('script.evaluate', { + expression: `Promise.resolve(${expression}).then((v) => JSON.stringify(v === undefined ? null : v))`, + target: { context: t.context }, + awaitPromise: true, + }); + if (r.type === 'exception') throw new Error(r.exceptionDetails?.text || 'script failed'); + return JSON.parse(r.result.value); + }; + return { + evaluate, + waitFor: waitFor(evaluate), + navigate: t.navigate, + screenshot: t.screenshot, + click: async (x, y, { double = false, right = false } = {}) => { + const acts = [{ type: 'pointerMove', x, y }]; + for (let i = 0; i < (double ? 2 : 1); i++) { + acts.push({ type: 'pointerDown', button: right ? 2 : 0 }, { type: 'pointerUp', button: right ? 2 : 0 }); + } + await t.actions([{ type: 'pointer', id: 'mouse', parameters: { pointerType: 'mouse' }, actions: acts }]); + }, + key: async (key, mods = [], times = 1) => { + const m = mods.map((x) => KEYS[x].bidi); + const v = keyOf(key).bidi; + const acts = [...m.map((value) => ({ type: 'keyDown', value })), { type: 'keyDown', value: v }, { type: 'keyUp', value: v }, ...[...m].reverse().map((value) => ({ type: 'keyUp', value }))]; + for (let i = 0; i < times; i++) await t.actions([{ type: 'key', id: 'kb', actions: acts }]); + }, + setFiles: async (id, files) => { + const node = await ff.browser.send('script.evaluate', { + expression: `document.getElementById(${JSON.stringify(id)})`, target: { context: t.context }, awaitPromise: false, + }); + await ff.browser.send('input.setFiles', { context: t.context, element: { sharedId: node.result.sharedId }, files }); + }, + }; + }, + }; +} + +// ----- Chromium (DevTools protocol) ----------------------------------------------------------- + +async function chromium(port) { + const binary = process.env.CP_CHROME; + if (!binary) throw new Error('CP_CHROME: the Chromium / Chrome for Testing binary'); + const profile = mkdtempSync(join(process.env.TMPDIR || tmpdir(), 'cp-chrome-')); + const downloads = join(profile, 'downloads'); + mkdirSync(downloads, { recursive: true }); + const proc = spawn(binary, [ + '--headless=new', `--remote-debugging-port=${port}`, `--user-data-dir=${profile}`, + '--no-first-run', '--no-default-browser-check', '--disable-gpu-sandbox', '--use-angle=swiftshader', + '--enable-unsafe-swiftshader', 'about:blank', + ], { stdio: process.env.CP_CHROME_LOG ? 'inherit' : 'ignore' }); + let ws; + for (let i = 0; i < 300 && !ws; i++) { + try { + const v = await (await fetch(`http://127.0.0.1:${port}/json/version`)).json(); + ws = v.webSocketDebuggerUrl; + } catch { + await sleep(100); + } + } + if (!ws) throw new Error('Chromium did not start'); + const sock = new WebSocket(ws); + await new Promise((res) => (sock.onopen = res)); + let id = 0; + const pending = new Map(); + const listeners = []; + sock.onmessage = (m) => { + const d = JSON.parse(m.data); + if (d.id && pending.has(d.id)) { + const p = pending.get(d.id); + pending.delete(d.id); + d.error ? p.rej(new Error(d.error.message)) : p.res(d.result); + } else if (d.method) for (const l of listeners) l(d); + }; + const send = (method, params = {}, sessionId) => + new Promise((res, rej) => { + const i = ++id; + pending.set(i, { res, rej }); + sock.send(JSON.stringify({ id: i, method, params, sessionId })); + }); + await send('Browser.setDownloadBehavior', { behavior: 'allow', downloadPath: downloads }); + return { + name: 'chromium', + profile, + downloads, + send, + on: (f) => listeners.push(f), + stop: async () => { + try { sock.close(); } catch {} + try { process.kill(proc.pid); } catch {} + await sleep(500); + rmSync(profile, { recursive: true, force: true }); + }, + tab: async (width, height, log = console.log) => { + const { targetId } = await send('Target.createTarget', { url: 'about:blank' }); + const { sessionId } = await send('Target.attachToTarget', { targetId, flatten: true }); + const s = (method, params) => send(method, params, sessionId); + listeners.push((d) => { + if (d.sessionId !== sessionId) return; + if (d.method === 'Runtime.consoleAPICalled') { + log(`[${d.params.type}] ${d.params.args.map((a) => a.value ?? a.description ?? '').join(' ')}`); + } else if (d.method === 'Runtime.exceptionThrown') { + log(`[error] ${d.params.exceptionDetails.exception?.description || d.params.exceptionDetails.text}`); + } else if (d.method === 'Log.entryAdded' && d.params.entry.level === 'error') { + log(`[error] ${d.params.entry.text}`); + } + }); + await s('Page.enable'); + await s('Runtime.enable'); + await s('Log.enable'); + await s('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false }); + const evaluate = async (expression) => { + const r = await s('Runtime.evaluate', { expression: `Promise.resolve(${expression}).then((v) => JSON.stringify(v === undefined ? null : v))`, awaitPromise: true, returnByValue: true }); + if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description || r.exceptionDetails.text); + return JSON.parse(r.result.value); + }; + let modifiers = 0; + return { + sessionId, + send: s, + evaluate, + waitFor: waitFor(evaluate), + navigate: async (url) => { + await s('Page.navigate', { url }); + await waitFor(evaluate)(`document.readyState === 'complete'`, 30000); + }, + screenshot: async () => Buffer.from((await s('Page.captureScreenshot', { format: 'png' })).data, 'base64'), + click: async (x, y, { double = false, right = false } = {}) => { + const button = right ? 'right' : 'left'; + await s('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y }); + for (let i = 1; i <= (double ? 2 : 1); i++) { + await s('Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button, clickCount: i }); + await s('Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button, clickCount: i }); + } + }, + key: async (key, mods = [], times = 1) => { + for (let n = 0; n < times; n++) { + for (const m of mods) { + modifiers |= KEYS[m].mod; + await s('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: KEYS[m].key, code: KEYS[m].code, windowsVirtualKeyCode: KEYS[m].vk, modifiers }); + } + const k = keyOf(key); + const text = modifiers & 3 ? undefined : k.text; + await s('Input.dispatchKeyEvent', { type: text ? 'keyDown' : 'rawKeyDown', key: k.key, code: k.code, windowsVirtualKeyCode: k.vk, modifiers, text }); + await s('Input.dispatchKeyEvent', { type: 'keyUp', key: k.key, code: k.code, windowsVirtualKeyCode: k.vk, modifiers }); + for (const m of [...mods].reverse()) { + modifiers &= ~KEYS[m].mod; + await s('Input.dispatchKeyEvent', { type: 'keyUp', key: KEYS[m].key, code: KEYS[m].code, windowsVirtualKeyCode: KEYS[m].vk, modifiers }); + } + } + }, + setFiles: async (id, files) => { + const { result } = await s('Runtime.evaluate', { expression: `document.getElementById(${JSON.stringify(id)})` }); + await s('DOM.setFileInputFiles', { objectId: result.objectId, files }); + }, + }; + }, + }; +} + +export async function open(port, kind = process.env.CP_BROWSER || 'firefox') { + return kind === 'chromium' ? chromium(port) : firefox(port); +} diff --git a/apps/web/check/review.mjs b/apps/web/check/review.mjs index 335b279..07a71c6 100644 --- a/apps/web/check/review.mjs +++ b/apps/web/check/review.mjs @@ -35,10 +35,7 @@ try { // The games in one file, reviewed one by one. await s.run({ key: 'o', mods: ['ctrl'] }, outDir); await t.waitFor(`!!document.getElementById('cp-open-files')`, 5000); - const input = await s.ff.browser.send('script.evaluate', { - expression: `document.getElementById('cp-open-files')`, target: { context: t.context }, awaitPromise: false, - }); - await s.ff.browser.send('input.setFiles', { context: t.context, element: { sharedId: input.result.sharedId }, files: [all] }); + await t.setFiles('cp-open-files', [all]); await sleep(3000); await s.run({ shot: 'review-0-opened.png' }, outDir); for (let i = 0; i < games.length; i++) { diff --git a/apps/web/check/shot.mjs b/apps/web/check/shot.mjs deleted file mode 100644 index 10395ea..0000000 --- a/apps/web/check/shot.mjs +++ /dev/null @@ -1,18 +0,0 @@ -// A screenshot of a page of the web version in headless Firefox, with its console: -// -// node apps/web/check/shot.mjs [wait-ms] [width] [height] -import { writeFileSync } from 'node:fs'; -import { launch } from './firefox.mjs'; -import { sleep, tab } from './bidi.mjs'; - -const [url, out, wait = '6000', width = '1400', height = '860'] = process.argv.slice(2); -const ff = await launch(); -try { - const t = await tab(ff.browser, Number(width), Number(height)); - await t.navigate(url); - await sleep(Number(wait)); - writeFileSync(out, await t.screenshot()); - console.log('saved', out); -} finally { - await ff.stop(); -} diff --git a/apps/web/check/stage2.mjs b/apps/web/check/stage2.mjs index 077005a..64b7a01 100644 --- a/apps/web/check/stage2.mjs +++ b/apps/web/check/stage2.mjs @@ -52,17 +52,14 @@ try { await step({ shot: 's2-4-settings.png' }); await step({ click: [1366, 77] }); // Two files opened; one kept as a copy. - const a = join(s.ff.profile, 'Kept games.pgn'); - const b = join(s.ff.profile, 'Visit games.pgn'); + const a = join(s.b.profile, 'Kept games.pgn'); + const b = join(s.b.profile, 'Visit games.pgn'); copyFileSync(join(root, 'examples/alekhine.pgn'), a); copyFileSync(join(root, 'examples/classics.pgn'), b); for (const file of [b, a]) { await step({ key: 'o', mods: ['ctrl'] }); await t.waitFor(`!!document.getElementById('cp-open-files')`, 5000); - const input = await s.ff.browser.send('script.evaluate', { - expression: `document.getElementById('cp-open-files')`, target: { context: t.context }, awaitPromise: false, - }); - await s.ff.browser.send('input.setFiles', { context: t.context, element: { sharedId: input.result.sharedId }, files: [file] }); + await t.setFiles('cp-open-files', [file]); await sleep(2500); } await step({ shot: 's2-5-opened.png' }); diff --git a/apps/web/check/steps.mjs b/apps/web/check/steps.mjs index eb797f8..a32eadf 100644 --- a/apps/web/check/steps.mjs +++ b/apps/web/check/steps.mjs @@ -1,27 +1,26 @@ -// Runs a list of steps in the web version in headless Firefox and keeps screenshots — -// for finding the places of buttons, and for the scenario checks built on it. +// A session of the web version in a headless browser (browser.mjs: Firefox, or +// Chromium with CP_BROWSER=chromium) over the site's layout (serve.py), and a runner of +// step lists — for finding the places of buttons, and for the scenario checks. // // node apps/web/check/steps.mjs // // A step: {"url": "?lang=en"} | {"wait": ms} | {"click": [x, y], "double": true} -// | {"key": "l", "mods": ["ctrl"]} | {"shot": "name.png"} | {"eval": "js expression"} +// | {"key": "l", "mods": ["ctrl"], "times": 3} | {"shot": "name.png"} | {"eval": "js"} // | {"until": "js expression", "ms": 60000} import { spawn } from 'node:child_process'; import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import { join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; -import { launch } from './firefox.mjs'; -import { sleep, tab } from './bidi.mjs'; - -export const KEYS = { ctrl: '', shift: '', alt: '', esc: '', right: '', left: '', enter: '' }; +import { open } from './browser.mjs'; +import { sleep } from './bidi.mjs'; export async function session(appDir, port = Number(process.env.CP_CHECK_PORT || 18767)) { const root = fileURLToPath(new URL('../../..', import.meta.url)); const server = spawn('python3', ['-I', join(root, 'apps/web/check/serve.py'), resolve(appDir), join(root, 'website/static'), String(port)], { stdio: 'ignore' }); - const ff = await launch(port + 457); + const b = await open(port + 457); const errors = []; - const t = await tab(ff.browser, 1400, 860, (line) => { - if (/panicked|RuntimeError|\[error\]/.test(line)) errors.push(line); + const t = await b.tab(1400, 860, (line) => { + if (/panicked|RuntimeError|\[error\]/.test(line) && !/favicon|404/.test(line)) errors.push(line); if (process.env.CONSOLE) console.log(line); }); const base = `http://127.0.0.1:${port}/app/`; @@ -32,17 +31,11 @@ export async function session(appDir, port = Number(process.env.CP_CHECK_PORT || } if (step.wait) await sleep(step.wait); if (step.click) { - const [x, y] = step.click; - const acts = [{ type: 'pointerMove', x, y }]; - for (let i = 0; i < (step.double ? 2 : 1); i++) acts.push({ type: 'pointerDown', button: step.right ? 2 : 0 }, { type: 'pointerUp', button: step.right ? 2 : 0 }); - await t.actions([{ type: 'pointer', id: 'mouse', parameters: { pointerType: 'mouse' }, actions: acts }]); + await t.click(step.click[0], step.click[1], step); await sleep(300); } if (step.key) { - const mods = (step.mods || []).map((m) => KEYS[m]); - const v = KEYS[step.key] || step.key; - const acts = [...mods.map((m) => ({ type: 'keyDown', value: m })), { type: 'keyDown', value: v }, { type: 'keyUp', value: v }, ...mods.reverse().map((m) => ({ type: 'keyUp', value: m }))]; - for (let i = 0; i < (step.times || 1); i++) await t.actions([{ type: 'key', id: 'kb', actions: acts }]); + await t.key(step.key, step.mods || [], step.times || 1); await sleep(300); } if (step.eval) console.log('eval:', JSON.stringify(await t.evaluate(step.eval)).slice(0, 2000)); @@ -50,8 +43,8 @@ export async function session(appDir, port = Number(process.env.CP_CHECK_PORT || if (step.shot) writeFileSync(join(outDir, step.shot), await t.screenshot()); }; return { - t, ff, errors, run, - stop: async () => { await ff.stop(); server.kill(); }, + t, b, base, errors, run, + stop: async () => { await b.stop(); server.kill(); }, }; }