425 lines
29 KiB
TypeScript
425 lines
29 KiB
TypeScript
// Drives Chromium (the browser the app is used in) and Firefox against a running Booksorter server.
|
|
// Usage: node scripts/browser-check.ts [baseUrl] (point the server at a scratch database)
|
|
// npx playwright install chromium firefox # once
|
|
// PORT=4323 BOOKSORTER_DB=/tmp/scratch.db npm start # in another terminal
|
|
// Env: SHOTS=<dir> saves 1280px dark-mode screenshots; ISBN=<isbn13> uses another already-resolved book.
|
|
// The camera is Chromium's fake camera playing a .y4m video of an EAN-13 barcode that this script renders.
|
|
// It adds, removes and re-adds the test book, and invents a few books in the page (never on the server) to
|
|
// hold the "looking up" and "needs attention" states still.
|
|
import { chromium, firefox } from 'playwright';
|
|
import type { Browser, BrowserContext, Page } from 'playwright';
|
|
import { build } from 'esbuild';
|
|
import { mkdirSync, mkdtempSync } from 'node:fs';
|
|
import { tmpdir } from 'node:os';
|
|
import { join } from 'node:path';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { makeBarcodeY4m } from './browser-media.ts';
|
|
|
|
const base = process.argv[2] ?? 'http://localhost:4321';
|
|
if (new URL(base).port === '4321' && !process.env.ALLOW_4321) { console.error('Refusing to run against port 4321 (the real database). Use a scratch server.'); process.exit(2); }
|
|
const shots = process.env.SHOTS;
|
|
if (shots) mkdirSync(shots, { recursive: true });
|
|
const ISBN = process.env.ISBN ?? '9781593278281';
|
|
const ISBN2 = '9780201835953'; // used only for invented books, never looked up
|
|
const root = fileURLToPath(new URL('..', import.meta.url));
|
|
const work = mkdtempSync(join(tmpdir(), 'booksorter-check-'));
|
|
|
|
const failures: string[] = [];
|
|
const check = (name: string, ok: boolean, detail = '') => {
|
|
console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail ? ' ' + detail : ''}`);
|
|
if (!ok) failures.push(name);
|
|
};
|
|
const norm = (s: string) => s.replace(/\s+/g, ' ').trim();
|
|
|
|
const consoleErrors: string[] = [];
|
|
const badRequests: string[] = [];
|
|
const foreign: string[] = [];
|
|
function watch(page: Page, label: string) {
|
|
page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(`${label}: ${m.text()}`); });
|
|
page.on('pageerror', (e) => consoleErrors.push(`${label}: ${e}`));
|
|
page.on('requestfailed', (r) => badRequests.push(`${label}: ${r.url()} ${r.failure()?.errorText}`));
|
|
page.on('response', (r) => { if (r.status() >= 400) badRequests.push(`${label}: ${r.url()} ${r.status()}`); });
|
|
page.on('request', (r) => {
|
|
const u = new URL(r.url());
|
|
if (!['localhost', '127.0.0.1'].includes(u.hostname) && !['blob:', 'data:', 'about:'].includes(u.protocol)) foreign.push(r.url());
|
|
});
|
|
}
|
|
const shot = async (page: Page, name: string) => { if (shots) await page.screenshot({ path: `${shots}/${name}.png`, fullPage: true }); };
|
|
const section = async (name: string, fn: () => Promise<void>) => {
|
|
console.log(`\n# ${name}`);
|
|
try { await fn(); } catch (e) { check(`${name}: ran to completion`, false, String(e).split('\n')[0]); }
|
|
};
|
|
|
|
const api = <T = any>(page: Page, path: string, init?: { method?: string; body?: unknown }): Promise<T> =>
|
|
page.evaluate(async ({ path, init }) => {
|
|
const r = await fetch(path, { method: init?.method ?? 'GET', headers: init?.body ? { 'Content-Type': 'application/json' } : undefined, body: init?.body ? JSON.stringify(init.body) : undefined });
|
|
const t = await r.text();
|
|
return t ? JSON.parse(t) : null;
|
|
}, { path, init });
|
|
|
|
const removeBook = (page: Page, isbn: string) => page.evaluate(async (isbn) => {
|
|
const books = await (await fetch('/api/books?filter=all')).json();
|
|
for (const b of books.filter((x: any) => x.isbn13 === isbn)) await fetch(`/api/books/${b.id}`, { method: 'DELETE' });
|
|
}, isbn);
|
|
|
|
const fakeBook = (id: number, over: Record<string, unknown>) => ({
|
|
id, isbn13: null, lccn: null, title: `Book ${id}`, subtitle: null, authors: ['A. Writer'], publisher: null, year: null, subjects: [],
|
|
callNumber: null, sortKey: null, confidence: null, source: null, dewey: null, status: 'pending', attentionReason: null,
|
|
manualOverride: false, inQueue: true, printedAt: null, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), ...over,
|
|
});
|
|
|
|
/** Answer POST /api/scan for one ISBN with an invented book instead of asking the server. */
|
|
async function inventScan(page: Page, isbn: string, book: Record<string, unknown>) {
|
|
await page.route('**/api/scan', async (route) => {
|
|
const sent = route.request().postDataJSON();
|
|
if (sent?.isbn === isbn) await route.fulfill({ json: { book, duplicate: false } });
|
|
else await route.fallback();
|
|
});
|
|
}
|
|
|
|
const rows = (page: Page) => page.locator('.scan .right li.book');
|
|
const statusLine = (page: Page) => page.getByRole('status').filter({ hasText: /\S/ }).first();
|
|
|
|
// Bundle the production scanner so a page can call its decode functions directly.
|
|
const bundled = await build({
|
|
stdin: { contents: "export * from './src/web/scanner.ts';", resolveDir: root, loader: 'ts' },
|
|
bundle: true, format: 'esm', write: false, target: 'es2022', logLevel: 'silent',
|
|
});
|
|
const scannerJs = bundled.outputFiles[0].text.replaceAll('https://fastly.jsdelivr.net/npm/', '/local-only/');
|
|
|
|
// Videos for the fake camera: a barcode on white at a readable size, a hard (small, soft) one, and an empty page.
|
|
const videoOk = join(work, 'barcode.y4m');
|
|
const videoHard = join(work, 'barcode-small.y4m');
|
|
const videoBlank = join(work, 'blank.y4m');
|
|
makeBarcodeY4m(videoOk, { isbn: ISBN, moduleScale: 2.0, frames: 24 });
|
|
makeBarcodeY4m(videoHard, { isbn: ISBN, moduleScale: 1.6, frames: 24 });
|
|
makeBarcodeY4m(videoBlank, { isbn: ISBN, moduleScale: 0.01, frames: 4 });
|
|
|
|
const chromiumFor = (video: string) => chromium.launch({
|
|
headless: true,
|
|
args: ['--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream', `--use-file-for-fake-video-capture=${video}`],
|
|
});
|
|
const darkContext = (b: Browser, extra: Parameters<Browser['newContext']>[0] = {}) =>
|
|
b.newContext({ viewport: { width: 1280, height: 900 }, colorScheme: 'dark', permissions: ['camera'], ...extra });
|
|
|
|
/** Records every stream the page opens, and every change of the status line, for later assertions. */
|
|
const instrument = (ctx: BrowserContext, gumDelayMs = 0) => ctx.addInitScript((delay) => {
|
|
const w = window as any;
|
|
w.__streams = []; w.__statuses = []; w.__flashes = 0;
|
|
const md = navigator.mediaDevices;
|
|
const orig = md.getUserMedia.bind(md);
|
|
md.getUserMedia = async (c) => {
|
|
if (delay) await new Promise((r) => setTimeout(r, delay));
|
|
const s = await orig(c); w.__streams.push(s); return s;
|
|
};
|
|
new MutationObserver((list) => {
|
|
for (const m of list) {
|
|
const t = m.target as HTMLElement;
|
|
if (t.classList?.contains('video-wrap') && t.classList.contains('flash')) w.__flashes++;
|
|
}
|
|
const st = document.querySelector('p.status');
|
|
if (st && st.textContent && w.__statuses[w.__statuses.length - 1] !== st.textContent) w.__statuses.push(st.textContent);
|
|
}).observe(document, { subtree: true, childList: true, attributes: true, characterData: true });
|
|
}, gumDelayMs);
|
|
const liveTracks = (page: Page) => page.evaluate(() => (window as any).__streams.flatMap((s: MediaStream) => s.getTracks()).filter((t: MediaStreamTrack) => t.readyState === 'live').length);
|
|
|
|
let server404 = false;
|
|
try { const r = await fetch(base); server404 = !r.ok; } catch { server404 = true; }
|
|
if (server404) { console.error(`No Booksorter server answering at ${base}`); process.exit(2); }
|
|
|
|
// ---------------------------------------------------------------------------------------------------
|
|
// 1. Typed ISBNs: one Enter is one request and one row (Chromium and Firefox)
|
|
// ---------------------------------------------------------------------------------------------------
|
|
for (const [name, type] of [['chromium', chromium], ['firefox', firefox]] as const) {
|
|
await section(`${name}: typed ISBN`, async () => {
|
|
const browser = await type.launch({ headless: true });
|
|
const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 }, colorScheme: 'dark' });
|
|
const page = await ctx.newPage(); watch(page, name);
|
|
const posts: string[] = [];
|
|
page.on('request', (r) => { if (r.url().endsWith('/api/scan') && r.method() === 'POST') posts.push(r.postData() ?? ''); });
|
|
await page.goto(base, { waitUntil: 'networkidle' });
|
|
await removeBook(page, ISBN); // the lookup cache makes the re-add quick; a scratch database is assumed
|
|
const box = page.getByLabel('ISBN');
|
|
check('ISBN box is focused on load', await box.evaluate((el) => el === document.activeElement));
|
|
check('page loads, Scan tab renders', await page.getByRole('heading', { name: 'This session' }).isVisible());
|
|
await box.fill(ISBN);
|
|
await box.press('Enter');
|
|
await rows(page).first().waitFor();
|
|
await page.waitForTimeout(700);
|
|
check('one typed ISBN + Enter sends exactly one POST /api/scan', posts.length === 1, `${posts.length} request(s)`);
|
|
check('one typed ISBN makes exactly one row', (await rows(page).count()) === 1);
|
|
await rows(page).first().locator('[data-state]').or(rows(page).first()).first().waitFor();
|
|
await page.locator('.scan .right li.book:not(.looking)').first().waitFor({ timeout: 150_000 });
|
|
const text = norm(await rows(page).first().innerText());
|
|
check('the row shows one state', /Ready|Needs attention/.test(text) && !/Looking up/.test(text), text.slice(0, 120));
|
|
|
|
await box.fill(ISBN);
|
|
await box.press('Enter');
|
|
await page.waitForTimeout(800);
|
|
check('typing the same ISBN again leaves one row', (await rows(page).count()) === 1, `${await rows(page).count()} row(s), ${posts.length} POSTs`);
|
|
check('the book already in this session is not marked "Already in catalog"', !/Already in catalog/.test(await rows(page).first().innerText()));
|
|
|
|
// Two Enters while the first request is still in flight: still one request, one row.
|
|
await page.route('**/api/scan', async (route) => { await new Promise((r) => setTimeout(r, 600)); await route.fallback(); });
|
|
const before = posts.length;
|
|
await box.fill(ISBN); await box.press('Enter');
|
|
await box.fill(ISBN); await box.press('Enter');
|
|
await page.waitForTimeout(1500);
|
|
check('two quick Enters for one ISBN send one request', posts.length - before === 1, `${posts.length - before} request(s)`);
|
|
check('and still one row', (await rows(page).count()) === 1);
|
|
|
|
// Reload: the book is now an earlier one, so it is shown once with the note.
|
|
await page.reload({ waitUntil: 'networkidle' });
|
|
await page.getByLabel('ISBN').fill(ISBN); await page.getByLabel('ISBN').press('Enter');
|
|
await rows(page).first().waitFor();
|
|
const earlier = norm(await rows(page).first().innerText());
|
|
check('a book from an earlier session shows one row with "Already in catalog"', (await rows(page).count()) === 1 && /Already in catalog/.test(earlier), earlier.slice(0, 120));
|
|
await browser.close();
|
|
});
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------------------------------
|
|
// 2. States, summary, queue (Chromium, invented books for the states that cannot be held still for real)
|
|
// ---------------------------------------------------------------------------------------------------
|
|
await section('session states, summary and print queue', async () => {
|
|
const browser = await chromium.launch({ headless: true });
|
|
const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 }, colorScheme: 'dark' });
|
|
const page = await ctx.newPage(); watch(page, 'states');
|
|
await page.goto(base, { waitUntil: 'networkidle' });
|
|
await removeBook(page, ISBN);
|
|
const pendingBook = fakeBook(900001, { isbn13: ISBN2, title: 'The Mythical Man-Month', authors: ['Frederick P. Brooks'], attentionReason: 'Library of Congress did not answer. Trying again shortly.' });
|
|
await inventScan(page, ISBN2, pendingBook);
|
|
const attentionBook = fakeBook(900002, { isbn13: null, title: 'A Book Nobody Catalogued', authors: ['Anon.'], status: 'needs_attention', attentionReason: 'No catalog record matched this ISBN.', inQueue: false });
|
|
await page.route('**/api/books/lccn', (route) => route.fulfill({ json: { book: attentionBook } }));
|
|
|
|
// Ready book 1: typed ISBN (resolved from cache). Ready book 2: entered by hand with a call number.
|
|
const box = page.getByLabel('ISBN');
|
|
await box.fill(ISBN); await box.press('Enter');
|
|
await page.locator('.scan .right li.book.ready').first().waitFor({ timeout: 150_000 });
|
|
await page.locator('summary', { hasText: 'Enter by hand' }).click();
|
|
const manual = page.locator('details', { hasText: 'Enter by hand' });
|
|
await manual.getByLabel('Title').fill('Structure and Interpretation of Computer Programs');
|
|
await manual.getByLabel('Authors (separate with ;)').fill('Harold Abelson; Gerald Jay Sussman');
|
|
await manual.getByLabel('Call number (optional)').fill('QA76.6 .A24 1996');
|
|
await manual.getByRole('button', { name: 'Add' }).click();
|
|
await page.locator('.scan .right li.book.ready', { hasText: 'Structure and Interpretation' }).waitFor();
|
|
// Looking-up book (invented scan), and a needs-attention book (invented LCCN answer).
|
|
await box.fill(ISBN2); await box.press('Enter');
|
|
await rows(page).first().waitFor();
|
|
await page.locator('summary', { hasText: 'Enter LCCN' }).click();
|
|
const lccn = page.locator('details', { hasText: 'Enter LCCN' });
|
|
await lccn.getByLabel('LCCN').fill('00000000');
|
|
await lccn.getByRole('button', { name: 'Add' }).click();
|
|
await page.locator('.scan .right li.book.attention').waitFor();
|
|
await page.waitForTimeout(2200); // let the seconds count
|
|
|
|
const summary = norm(await page.locator('.scan .summary').innerText());
|
|
check('summary counts all four rows', summary === '4 scanned · 2 ready · 1 looking up · 1 needs attention', summary);
|
|
const looking = rows(page).filter({ hasText: 'Looking up' });
|
|
const lookingText = norm(await looking.innerText());
|
|
check('a pending book shows Looking up with elapsed seconds', /Looking up… \d+ s/.test(lookingText), lookingText);
|
|
check('a pending book shows its retry note', lookingText.includes('Trying again shortly'));
|
|
check('a pending book never says "No call number"', !/No call number/.test(lookingText));
|
|
check('a pending book has a spinner', (await looking.locator('.spinner').count()) === 1);
|
|
const secs = Number(/(\d+) s/.exec(lookingText)?.[1] ?? 0);
|
|
check('the elapsed seconds are counting', secs >= 2, `${secs} s`);
|
|
const attn = norm(await rows(page).filter({ hasText: 'Needs attention' }).innerText());
|
|
check('a needs-attention row shows the reason and a Fix button', attn.includes('No catalog record matched') && attn.includes('Fix'), attn);
|
|
check('every row shows exactly one state label',
|
|
(await rows(page).evaluateAll((els) => els.map((e) => e.querySelectorAll('.state-label').length))).every((n) => n === 1));
|
|
await rows(page).filter({ hasText: 'Needs attention' }).getByRole('button', { name: 'Fix' }).click();
|
|
check('Fix opens the editor', await page.getByLabel('Call number', { exact: true }).isVisible());
|
|
// The year field rejects text, never sends NaN.
|
|
let patched = false;
|
|
await page.route('**/api/books/900002', async (route) => { patched = true; await route.fulfill({ json: attentionBook }); });
|
|
await page.locator('.editor').getByLabel('Year').fill('abc');
|
|
await page.locator('.editor').getByRole('button', { name: 'Save' }).click();
|
|
check('the editor shows an error for a non-numeric year and sends nothing', (await page.locator('.editor [role=alert]').first().isVisible()) && !patched);
|
|
await page.locator('.editor').getByLabel('Year').fill('');
|
|
await page.locator('.editor').getByRole('button', { name: 'Save' }).click();
|
|
await page.waitForTimeout(300);
|
|
check('an empty year is saved as null', patched);
|
|
await shot(page, 'scan-three-states');
|
|
|
|
// Print queue
|
|
const readyCount = (await api<any[]>(page, '/api/books?filter=queue')).filter((b) => b.status === 'resolved' && b.callNumber).length;
|
|
await page.getByRole('tab', { name: /^Print queue/ }).click();
|
|
await page.getByRole('heading', { name: 'Print queue' }).waitFor();
|
|
const head = norm(await page.locator('.queue .summary').innerText());
|
|
const want = `${readyCount} ${readyCount === 1 ? 'card' : 'cards'} ready · 1 still looking up`;
|
|
check('queue header counts ready and looking-up books', head === want, `${head} (expected ${want})`);
|
|
check('the pending book is listed in the queue, greyed, with the spinner', (await page.locator('.queue li.item.dim .spinner').count()) === 1);
|
|
check('the tab label counts queued books (ready + looking up)', norm(await page.getByRole('tab', { name: /^Print queue/ }).innerText()) === `Print queue (${readyCount + 1})`);
|
|
check('"Needs attention" does not claim every book has a call number', !/Every book has a call number/.test(await page.locator('.queue').innerText()));
|
|
const pdfBtn = page.getByRole('button', { name: /^Make PDF/ });
|
|
check('Make PDF says how many cards', norm(await pdfBtn.innerText()) === `Make PDF (${readyCount} ${readyCount === 1 ? 'card' : 'cards'})`, norm(await pdfBtn.innerText()));
|
|
await shot(page, 'queue-ready-and-looking');
|
|
const [pdfResp] = await Promise.all([page.waitForResponse((r) => r.url().includes('/api/print.pdf')), pdfBtn.click()]);
|
|
const body = await pdfResp.body();
|
|
check('Make PDF fetches a PDF', pdfResp.status() === 200 && body.subarray(0, 4).toString() === '%PDF', `${body.length} bytes`);
|
|
await page.getByText('Did the cards print correctly?').waitFor();
|
|
await page.getByRole('button', { name: 'Not yet' }).click();
|
|
await shot(page, 'queue-after-pdf');
|
|
const catalog = page.getByRole('tab', { name: /^Catalog/ });
|
|
await catalog.click();
|
|
await page.waitForTimeout(400);
|
|
check('Catalog tab renders', (await page.locator('main').innerText()).trim().length > 0);
|
|
await browser.close();
|
|
});
|
|
|
|
await section('print queue with nothing ready', async () => {
|
|
const browser = await chromium.launch({ headless: true });
|
|
const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 }, colorScheme: 'dark' });
|
|
const page = await ctx.newPage(); watch(page, 'empty-queue');
|
|
// Show only a pending book: the server's list is answered by an invented one.
|
|
await page.route('**/api/books?*', (route) => route.fulfill({ json: [fakeBook(900003, { title: 'Still Looking' })] }));
|
|
await page.goto(base, { waitUntil: 'networkidle' });
|
|
await page.getByRole('tab', { name: /^Print queue/ }).click();
|
|
const head = norm(await page.locator('.queue .summary').innerText());
|
|
check('queue with only a pending book reads "0 cards ready · 1 still looking up"', head === '0 cards ready · 1 still looking up', head);
|
|
const pdfBtn = page.getByRole('button', { name: /^Make PDF/ });
|
|
check('Make PDF is disabled with an explanation', (await pdfBtn.isDisabled()) && (await page.locator('#pdf-why').innerText()).includes('No card is ready yet'));
|
|
check('the tab label says (1)', norm(await page.getByRole('tab', { name: /^Print queue/ }).innerText()) === 'Print queue (1)');
|
|
await browser.close();
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------------------------------
|
|
// 3. The camera, in Chromium with a fake camera playing a video of a barcode
|
|
// ---------------------------------------------------------------------------------------------------
|
|
await section('camera: Start camera reads the barcode from video alone', async () => {
|
|
const browser = await chromiumFor(videoOk);
|
|
const ctx = await darkContext(browser);
|
|
await instrument(ctx);
|
|
const page = await ctx.newPage(); watch(page, 'camera');
|
|
const posts: string[] = [];
|
|
page.on('request', (r) => { if (r.url().endsWith('/api/scan') && r.method() === 'POST') posts.push(r.postData() ?? ''); });
|
|
await page.goto(base, { waitUntil: 'networkidle' });
|
|
await removeBook(page, ISBN);
|
|
check('camera off: Start camera is in the middle of the video area', await page.locator('.video-empty').getByRole('button', { name: 'Start camera' }).isVisible());
|
|
check('camera off: the status line says so', /camera is off/i.test(await statusLine(page).innerText()));
|
|
|
|
await page.getByRole('button', { name: 'Start camera' }).dblclick(); // a double click must not open two streams
|
|
await page.getByText('Hold the barcode inside the box').waitFor({ timeout: 20_000 });
|
|
check('the target box and instruction are shown', await page.locator('.target').isVisible());
|
|
check('the Scanning indicator is shown', await page.locator('.scanning').isVisible());
|
|
await page.waitForFunction(() => (window as any).__statuses.some((s: string) => /^Read \d{13}$/.test(s)), null, { timeout: 30_000 });
|
|
const statuses: string[] = await page.evaluate(() => (window as any).__statuses);
|
|
check('status line went "Looking for a barcode…" then "Read <isbn>"', statuses.includes('Looking for a barcode…') && statuses.includes(`Read ${ISBN}`), JSON.stringify(statuses));
|
|
check('the video border flashed green on the read', (await page.evaluate(() => (window as any).__flashes)) >= 1);
|
|
await rows(page).first().waitFor({ timeout: 15_000 });
|
|
await page.waitForTimeout(1500);
|
|
check('the book appeared in the session list from the camera alone, one row', (await rows(page).count()) === 1, norm(await rows(page).first().innerText()).slice(0, 100));
|
|
check('a barcode held in view posts once, not once per frame', posts.length === 1, `${posts.length} POST(s)`);
|
|
check('a double click on Start camera opened one stream', (await page.evaluate(() => (window as any).__streams.length)) === 1);
|
|
check('the video has real size', await page.evaluate(() => { const v = document.querySelector('video')!; return v.videoWidth > 0; }));
|
|
await shot(page, 'scan-camera-read');
|
|
|
|
// Capture button and Space
|
|
await page.waitForFunction(() => document.querySelector('p.status')?.textContent === 'Looking for a barcode…', null, { timeout: 10_000 });
|
|
const mark = await page.evaluate(() => (window as any).__statuses.length);
|
|
await page.getByRole('button', { name: 'Capture' }).click();
|
|
await page.waitForFunction((m) => (window as any).__statuses.slice(m).some((s: string) => /^Read \d{13}$/.test(s)), mark, { timeout: 20_000 });
|
|
const after: string[] = await page.evaluate((m) => (window as any).__statuses.slice(m), mark);
|
|
check('Capture takes a picture and reads the barcode', after[0] === 'Taking a picture and reading it…' && after.includes(`Read ${ISBN}`), JSON.stringify(after));
|
|
await page.waitForFunction(() => document.querySelector('p.status')?.textContent === 'Looking for a barcode…', null, { timeout: 10_000 });
|
|
const mark2 = await page.evaluate(() => (window as any).__statuses.length);
|
|
await page.locator('video').click({ force: true }); // focus leaves the text field
|
|
await page.evaluate(() => (document.activeElement as HTMLElement)?.blur?.());
|
|
await page.keyboard.press('Space');
|
|
await page.waitForFunction((m) => (window as any).__statuses.slice(m).includes('Taking a picture and reading it…'), mark2, { timeout: 10_000 });
|
|
check('Space triggers Capture when focus is not in a text field', true);
|
|
await page.waitForFunction((m) => (window as any).__statuses.slice(m).some((s: string) => /^Read \d{13}$/.test(s)), mark2, { timeout: 20_000 });
|
|
const box = page.getByLabel('ISBN');
|
|
await box.focus(); await page.keyboard.press('Space');
|
|
check('Space in the ISBN box also captures and types no space', (await box.inputValue()) === '');
|
|
check('the Capture reads never added a second row', (await rows(page).count()) === 1);
|
|
|
|
// Remembered: reload starts the camera by itself; Stop forgets it.
|
|
await page.reload({ waitUntil: 'networkidle' });
|
|
await page.getByRole('button', { name: 'Stop camera' }).waitFor({ timeout: 20_000 });
|
|
check('after a reload the camera starts by itself (permission already granted)', true);
|
|
await page.getByRole('button', { name: 'Stop camera' }).click();
|
|
await page.getByRole('button', { name: 'Start camera' }).waitFor();
|
|
check('Stop camera releases every stream', (await liveTracks(page)) === 0);
|
|
await page.reload({ waitUntil: 'networkidle' });
|
|
await page.waitForTimeout(800);
|
|
check('after Stop and a reload the camera stays off, with the Start button in the video area', await page.locator('.video-empty').getByRole('button', { name: 'Start camera' }).isVisible());
|
|
await browser.close();
|
|
});
|
|
|
|
await section('camera: leaving the view while the permission prompt is open', async () => {
|
|
const browser = await chromiumFor(videoOk);
|
|
const ctx = await darkContext(browser);
|
|
await instrument(ctx, 1500); // getUserMedia answers 1.5 s late, like a person reading the prompt
|
|
const page = await ctx.newPage(); watch(page, 'prompt');
|
|
await page.goto(base, { waitUntil: 'networkidle' });
|
|
const btn = page.getByRole('button', { name: /^Start camera|^Starting camera/ });
|
|
await btn.click();
|
|
check('Start is disabled while starting', await page.getByRole('button', { name: 'Starting camera…' }).isDisabled());
|
|
await page.getByRole('tab', { name: /^Print queue/ }).click(); // the Scan view unmounts mid-prompt
|
|
await page.waitForFunction(() => (window as any).__streams.length === 1, null, { timeout: 10_000 });
|
|
await page.waitForTimeout(300);
|
|
check('the stream that arrives after leaving is stopped at once', (await liveTracks(page)) === 0);
|
|
await browser.close();
|
|
});
|
|
|
|
await section('camera: nothing readable in view', async () => {
|
|
const browser = await chromiumFor(videoBlank);
|
|
const ctx = await darkContext(browser);
|
|
await instrument(ctx);
|
|
const page = await ctx.newPage(); watch(page, 'blank');
|
|
await page.goto(base, { waitUntil: 'networkidle' });
|
|
await page.getByRole('button', { name: 'Start camera' }).click();
|
|
await page.getByText('Hold the barcode inside the box').waitFor({ timeout: 20_000 });
|
|
await page.waitForTimeout(1000);
|
|
check('with no barcode the status stays "Looking for a barcode…"', (await statusLine(page).innerText()) === 'Looking for a barcode…');
|
|
await page.getByRole('button', { name: 'Capture' }).click();
|
|
await page.getByText('No barcode found in that picture. Move closer, add light, or type the ISBN below.').waitFor({ timeout: 20_000 });
|
|
check('Capture says plainly when it finds nothing', true);
|
|
check('and no row was added', (await rows(page).count()) === 0);
|
|
await browser.close();
|
|
});
|
|
|
|
await section('decoder: the thorough decode reads a small, soft barcode the live loop misses', async () => {
|
|
const browser = await chromiumFor(videoHard);
|
|
const ctx = await darkContext(browser);
|
|
const page = await ctx.newPage(); watch(page, 'decode');
|
|
await page.route('**/__check/scanner.js', (route) => route.fulfill({ contentType: 'text/javascript', body: scannerJs }));
|
|
await page.goto(base, { waitUntil: 'networkidle' });
|
|
const r = await page.evaluate(async (isbn) => {
|
|
const mod = await import(/* @vite-ignore */ ('/__check/' + 'scanner.js')); mod.prepare();
|
|
const stream = await navigator.mediaDevices.getUserMedia({ video: { width: 1920, height: 1080 } });
|
|
const v = document.createElement('video'); v.srcObject = stream; v.muted = true; await v.play();
|
|
await new Promise((res) => setTimeout(res, 500));
|
|
const live = await mod.decodeLive(v); const thorough = await mod.decodeThorough(v);
|
|
stream.getTracks().forEach((t: MediaStreamTrack) => t.stop());
|
|
return { live, thorough, isbn };
|
|
}, ISBN);
|
|
check('thorough decode reads the small barcode', r.thorough.isbn === ISBN, JSON.stringify(r));
|
|
check('live decode never returns a wrong ISBN for it', r.live.isbn === null || r.live.isbn === ISBN, JSON.stringify(r.live));
|
|
await browser.close();
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------------------------------
|
|
// 4. Firefox's fake camera starts and stops
|
|
// ---------------------------------------------------------------------------------------------------
|
|
await section('firefox: fake camera starts and stops', async () => {
|
|
const browser = await firefox.launch({ headless: true, firefoxUserPrefs: { 'media.navigator.streams.fake': true, 'media.navigator.permission.disabled': true } });
|
|
const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 }, colorScheme: 'dark' });
|
|
const page = await ctx.newPage(); watch(page, 'firefox-cam');
|
|
await page.goto(base, { waitUntil: 'networkidle' });
|
|
await page.getByRole('button', { name: 'Start camera' }).click();
|
|
await page.getByRole('button', { name: 'Stop camera' }).waitFor({ timeout: 20_000 });
|
|
check('Start camera plays video', await page.waitForFunction(() => { const v = document.querySelector('video') as HTMLVideoElement; return !!v.srcObject && v.videoWidth > 0 && !v.paused; }, null, { timeout: 15_000 }).then(() => true, () => false));
|
|
await page.getByRole('button', { name: 'Stop camera' }).click();
|
|
await page.getByRole('button', { name: 'Start camera' }).waitFor();
|
|
check('Stop camera releases the stream', await page.evaluate(() => !(document.querySelector('video') as HTMLVideoElement).srcObject));
|
|
await browser.close();
|
|
});
|
|
|
|
check('no console errors', consoleErrors.length === 0, consoleErrors.join(' | '));
|
|
check('no failed requests', badRequests.length === 0, badRequests.join(' | '));
|
|
check('no request left localhost', foreign.length === 0, foreign.join(' | '));
|
|
console.log(failures.length ? `\n${failures.length} check(s) failed: ${failures.join('; ')}` : '\nAll checks passed');
|
|
process.exit(failures.length ? 1 : 0);
|