gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmain0f6d1592Merge branch 'f18b-shell-session' into mainIdentmain/tests/e2e-usedin.mjs

12.8 KB

  1. // tests/e2e-usedin.mjs (ident#26, derived from e2e-theme.mjs): the theme move in a REAL browser (lisbeth's test Chrome over CDP, ONE existing tab reused,
  2. // never a new one), real mouse clicks and key events. Not a gate: prints numbers, writes screenshots.
  3. // node tests/e2e-theme.mjs <old|new> <port> <sink> <shotDir> <targetId> [cdpPort=8756]
  4. // ident runs on loreana on a COPY of the newest backup with a mail SINK file (never real mail), reached from lisbeth's Chrome through
  5. // `ssh -R <port>:127.0.0.1:<port>`. Per width (390, 1280): the signed-out pages, a real sign-in with the code read from the sink, the
  6. // 390 audit (tests/mobile-measure.js) of every page, then the walk: menus, sign out, register an app, an invite link, sign out everywhere.
  7. import { writeFileSync, readFileSync, existsSync } from 'node:fs';
  8. import { dirname, join } from 'node:path';
  9. import { fileURLToPath } from 'node:url';
  10. const [mode, port, sink, shotDir, tidArg, cdpPort = '8756'] = process.argv.slice(2); // tidArg: 'auto' = the first existing page tab, picked fresh from /json (never /json/new): an about:blank page, else a page of some worker's local test app (never a HyperConductor page)
  11. const BASE = `http://${process.env.E2E_HOST || '127.0.0.1'}:${port}`, sleep = ms => new Promise(r => setTimeout(r, ms)), J = JSON.stringify;
  12. const MEASURE = readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'mobile-measure.js'), 'utf8');
  13. const EMAIL = '[email protected]'; // an account of the COPY (real data: apps, connections, notifications); the code goes to the sink file
  14. const list = await (await fetch(`http://127.0.0.1:${cdpPort}/json/list`)).json();
  15. const tgt = tidArg && tidArg !== 'auto' ? list.find(t => t.id === tidArg) : (list.find(t => t.type === 'page' && t.url === 'about:blank') || list.find(t => t.type === 'page' && /^http:\/\/(127\.0\.0\.1|[a-z.]*localhost)[:\/]/.test(t.url)));
  16. const tid = tgt.id;
  17. const ws = new WebSocket(tgt.webSocketDebuggerUrl.replace(/ws:\/\/[^/]+/, `ws://127.0.0.1:${cdpPort}`)); await new Promise(r => ws.onopen = r);
  18. let id = 0; const pend = new Map(), consoleErrors = [], dialogTexts = [];
  19. ws.onmessage = m => { const d = JSON.parse(m.data);
  20. if (d.id && pend.has(d.id)) { const [ok, bad] = pend.get(d.id); pend.delete(d.id); d.error ? bad(new Error(J(d.error))) : ok(d.result); }
  21. else if (d.method === 'Page.javascriptDialogOpening') { dialogTexts.push(d.params.message); send('Page.handleJavaScriptDialog', { accept: true }).catch(() => {}); } // the person presses OK
  22. else if (d.method === 'Runtime.exceptionThrown') consoleErrors.push(J(d.params.exceptionDetails).slice(0, 200));
  23. else if (d.method === 'Runtime.consoleAPICalled' && d.params.type === 'error') consoleErrors.push(d.params.args.map(a => a.value || a.description).join(' ').slice(0, 200)); };
  24. const send = (method, params = {}) => new Promise((ok, bad) => { const i = ++id; pend.set(i, [ok, bad]); ws.send(J({ id: i, method, params })); });
  25. const ev = async x => { const r = await send('Runtime.evaluate', { expression: x, awaitPromise: true, returnByValue: true }); if (r.exceptionDetails) throw new Error(J(r.exceptionDetails).slice(0, 300)); return r.result.value; };
  26. const waitFor = async (x, label, t = 25000) => { for (const end = Date.now() + t; Date.now() < end;) { if (await ev(x).catch(() => false)) return true; await sleep(150); } console.log(' TIMEOUT', label); return false; };
  27. const rect = async sel => ev(`(() => { const e = document.querySelector(${J(sel)}); if (!e) return null; e.scrollIntoView({ block: 'center' }); const r = e.getBoundingClientRect(); return { x: r.x + r.width / 2, y: r.y + r.height / 2, w: r.width, h: r.height }; })()`);
  28. const click = async sel => { let r = await rect(sel); if (!r) throw new Error('no ' + sel); await sleep(120); r = await rect(sel); { const hit = await ev(`(() => { const t = document.querySelector(${J(sel)}); const h = document.elementFromPoint(${r.x}, ${r.y}); return t && h && (t === h || t.contains(h) || h.contains(t)) ? null : (h ? h.outerHTML.slice(0, 120) : 'nothing') + ' | vw=' + innerWidth + ' scrollY=' + scrollY; })()`).catch(() => null); if (hit) console.log(' CLICK COVERED', sel, hit); } for (const [type, extra] of [['mouseMoved', {}], ['mousePressed', { button: 'left', clickCount: 1 }], ['mouseReleased', { button: 'left', clickCount: 1 }]]) await send('Input.dispatchMouseEvent', { type, x: r.x, y: r.y, ...extra }); await sleep(150); const got = await ev('JSON.stringify(window.__got || [])').catch(() => '?'); if (got === '[]' || got === '?') console.log(' NO MOUSEDOWN reached the page after click on', sel, 'at', Math.round(r.x), Math.round(r.y), 'viewport', await ev('innerWidth + "x" + innerHeight + " dpr " + devicePixelRatio').catch(() => '?')); await ev('window.__got = []').catch(() => {}); };
  29. const key = async (k, code, vk) => { await send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: k, code, windowsVirtualKeyCode: vk }); await send('Input.dispatchKeyEvent', { type: 'keyUp', key: k, code, windowsVirtualKeyCode: vk }); };
  30. const typeInto = async (sel, text, clear = false) => { await click(sel); if (clear) { await send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'a', code: 'KeyA', windowsVirtualKeyCode: 65, modifiers: 2 }); await send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'a', code: 'KeyA', windowsVirtualKeyCode: 65, modifiers: 2 }); await key('Backspace', 'Backspace', 8); } for (const ch of text) { await send('Input.dispatchKeyEvent', { type: 'keyDown', text: ch, unmodifiedText: ch, key: ch }); await send('Input.dispatchKeyEvent', { type: 'keyUp', key: ch }); } };
  31. const shot = async name => { const r = await send('Page.captureScreenshot', { format: 'png' }); writeFileSync(`${shotDir}/${mode}-${name}.png`, Buffer.from(r.data, 'base64')); };
  32. const results = []; const check = (n, ok, d = '') => { results.push([n, !!ok]); console.log((ok ? 'PASS ' : 'FAIL ') + n + (ok ? '' : ' ' + d)); };
  33. const hydrated = () => waitFor(`!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1`, 'hydrated');
  34. const go = async (path, ready) => { await send('Page.navigate', { url: BASE + path }); await waitFor(`!!document.querySelector(${J(ready)})`, 'ready ' + ready + ' on ' + path); await hydrated(); await sleep(700); };
  35. const shows = sel => ev(`(() => { const e = document.querySelector(${J(sel)}); return !!e && e.getBoundingClientRect().width > 0; })()`);
  36. const txt = sel => ev(`(document.querySelector(${J(sel)}) || {}).textContent || ''`);
  37. const lastCode = (EM = EMAIL) => { const ls = existsSync(sink) ? readFileSync(sink, 'utf8').split('\n').filter(l => l.startsWith(EM + ' ')) : []; return ls.length ? ls.at(-1).split(' ')[1] : null; };
  38. const audits = [];
  39. async function audit(name, W) {
  40. const m = await ev(`window.__W = ${W};` + MEASURE);
  41. const r = { name, W, scrollWidth: m.docScrollWidth, taps: m.taps, tapsSmall: m.tapsSmall, small: m.tapsSmallList.slice(0, 6), inputsSmall: m.inputsSmall, inputsSmallList: m.inputsSmallList.slice(0, 4), textSmall: m.textSmall, textSmallList: m.textSmallList.slice(0, 4), wide: m.wide, wideList: m.wideList.slice(0, 3), header: m.headerH };
  42. audits.push(r); console.log('AUDIT', J(r)); await shot(`${W}-${name.replace(/[^a-z0-9]+/gi, '-')}`);
  43. }
  44. // THE SIGN-IN: email typed, "Send me a code" clicked, the code read from the sink like a person reads mail, typed, "Sign in" clicked
  45. async function signIn(W, EM = EMAIL) {
  46. await go('/', '#emailform');
  47. await typeInto('#email', EM); const before = lastCode(EM);
  48. await click('#sendcode'); await waitFor(`location.pathname === '/code' && !!document.querySelector('#code')`, 'code page'); await hydrated();
  49. for (let i = 0; i < 160 && lastCode(EM) === before; i++) await sleep(250);
  50. const c = lastCode(EM); check(`${W}: the sink got a 6-digit code`, /^\d{6}$/.test(c || ''), String(c));
  51. if (W) await audit('code-page', W);
  52. await typeInto('#code', c); await ev('window.__m = 1'); await click('#verify'); // __m survives only WITHOUT a reload (mission 013)
  53. const ok = await waitFor(`!!document.querySelector('#whoami')`, 'signed in');
  54. await hydrated(); return ok;
  55. }
  56. await send('Page.enable'); await send('Runtime.enable'); await send('DOM.enable'); await send('Network.enable');
  57. await send('Target.activateTarget', { targetId: tid }).catch(() => {});
  58. await send('Page.bringToFront');
  59. await send('Page.addScriptToEvaluateOnNewDocument', { source: "window.__got = []; addEventListener('mousedown', e => window.__got.push((e.target.tagName || '') + '#' + (e.target.id || '') + '@' + Math.round(e.clientX) + ',' + Math.round(e.clientY)), true);" });
  60. await send('Storage.clearDataForOrigin', { origin: BASE, storageTypes: 'service_workers,cache_storage,local_storage' }).catch(() => {});
  61. await send('Network.deleteCookies', { name: 'identsid', url: BASE }).catch(() => {});
  62. const view = async W => { if (W === 390) { await send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 2, mobile: true }); await send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 5 }); } else { await send('Emulation.setTouchEmulationEnabled', { enabled: false }); await send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false }); } await sleep(300); };
  63. const menuOpen = async (btn, pop) => { await click(btn); await waitFor(`document.querySelector(${J(pop)}).matches(':popover-open')`, pop + ' open'); await sleep(300); };
  64. const esc = async () => { await key('Escape', 'Escape', 27); await sleep(300); };
  65. try {
  66. for (const W of [390, 1280]) {
  67. await view(W); const T = `${W}-`; await send('Network.deleteCookies', { name: 'identsid', url: BASE }).catch(() => {});
  68. const ok = await signIn(0); check(`${T}${mode}: sign-in with a code from the sink`, ok && (await txt('#whoami')) === EMAIL, await txt('#whoami'));
  69. await go('/', '#identities'); await sleep(500);
  70. await shot(`identities-${W}`);
  71. const ids = await ev(`[...document.querySelectorAll('#identities li')].map(li => li.querySelector('identity-label').textContent).join(',')`);
  72. console.log(' identities:', ids);
  73. if (mode === 'new') {
  74. check(`${T}every identity has a "Used in…" link of at least 44 px`, await ev(`[...document.querySelectorAll('#identities li identity-actions a')].length === 3 && [...document.querySelectorAll('#identities li identity-actions a')].every(a => { const r = a.getBoundingClientRect(); return r.width >= 44 && r.height >= 44; })`));
  75. await click('#identities li:nth-child(1) identity-actions a');
  76. await waitFor(`location.pathname.startsWith('/identity/') && !!document.querySelector('#usedin')`, 'identity page'); await hydrated(); await sleep(500);
  77. const rows = await ev(`[...document.querySelectorAll('#usedin li')].map(li => li.querySelector('used-app').textContent + ' | ' + li.querySelector('used-line').textContent).join(' ## ')`);
  78. console.log(' rows:', rows);
  79. check(`${T}Default: at least one app, each with since + last use`, rows !== '' && rows.split(' ## ').every(r => / \| since [A-Z][a-z]{2} \d+ · last use (just now|\d+ (min|h|d) ago)$/.test(r)), rows);
  80. const firstApp = await txt('#usedin li:nth-child(1) used-app');
  81. check(`${T}no horizontal overflow`, await ev('document.documentElement.scrollWidth <= innerWidth'));
  82. check(`${T}every tap target on the page is >= 44 px`, await ev(`[...document.querySelectorAll('main a, main button')].every(e => { const r = e.getBoundingClientRect(); return r.width === 0 || (r.width >= 43.5 && r.height >= 43.5); })`));
  83. await shot(`used-in-${W}`);
  84. await click('#usedin li:nth-child(1) a');
  85. await waitFor(`location.pathname.startsWith('/inbox/') && !!document.querySelector('#connapp')`, 'per-app page'); await hydrated(); await sleep(400);
  86. check(`${T}"Notif." opens the per-app page (first row's app / Default)`, (await txt('#connapp')) === firstApp && (await txt('#connidentity')) === 'Default');
  87. await shot(`perapp-${W}`);
  88. await go('/', '#identities'); await click('#identities li:nth-child(3) identity-actions a');
  89. await waitFor(`!!document.querySelector('#usedinnone')`, 'empty state'); await sleep(400);
  90. check(`${T}Idle (never used): the empty-state text`, /Not used in any app yet/.test(await txt('#usedinnone')), await txt('ident-card'));
  91. await shot(`used-in-empty-${W}`);
  92. } else {
  93. // OLD: nothing to tap; the same URL does not exist
  94. const href = await ev(`document.querySelector('#identities li') ? 'present' : 'none'`);
  95. await go('/inbox', '#connsection'); await shot(`inbox-${W}`);
  96. }
  97. }
  98. } finally {
  99. console.log(`${mode}: ${results.filter(r => r[1]).length} passed, ${results.filter(r => !r[1]).length} failed; console errors: ${consoleErrors.length}`);
  100. for (const e of consoleErrors.slice(0, 5)) console.log(' console:', e);
  101. await send('Emulation.clearDeviceMetricsOverride').catch(() => {});
  102. await send('Emulation.setTouchEmulationEnabled', { enabled: false }).catch(() => {});
  103. ws.close();
  104. process.exit(results.some(r => !r[1]) ? 1 : 0);
  105. }

Branches

Latest commits

  • 0f6d1592Merge branch 'f18b-shell-session' into mainIdent
  • 19868218|||PR ident#39 shell reads its session member instead of a cross-file emitmre
  • 5d1b3fedMerge branch 'v61-day61' into mainIdent
  • 83faeb15|||PR ident: vendor Hybriel day61mre
  • b2572b34Merge branch 'v59-day59' into mainIdent
  • 67cf016d|||PR ident: vendor Hybriel day59mre
  • 600c043dMerge branch 'v58-day58' into mainIdent
  • 365f8c80|||PR ident: vendor Hybriel day58mre
  • 585126e5Merge branch 'f16-setf' into mainIdent
  • 953bf03a|||PR ident setF mirror dropped (hybriel#370)mre
  • a1419d9cMerge branch 'f15-navigate' into mainIdent
  • 3b3e451f|||PR ident#36 navigate to the app instead of location.assignmre
  • e36f4516Merge branch 'f14-online' into mainIdent
  • 2c5eac91|||PR ident#38 online state without probe timermre
  • bf1980f2Merge branch 'v56-day56' into mainIdent
  • 62ae0adf|||PR ident: vendor Hybriel day56mre
  • 0d18abc4Merge branch 'f13-avatar' into mainIdent
  • 2a99730a|||PR ident#37 avatar in hlmre
  • fa4ed25bMerge branch 'f11-upsert' into mainIdent
  • 8f3d9bc9|||PR ident#42 keyed upsert and removemre