ident
All repositories: gitoria
16.4 KB
// tests/e2e-theme.mjs (ident mission 012): the theme move in a REAL browser (lisbeth's test Chrome over CDP, ONE existing tab reused,// never a new one), real mouse clicks and key events. Not a gate: prints numbers, writes screenshots.// node tests/e2e-theme.mjs <old|new> <port> <sink> <shotDir> <targetId> [cdpPort=8756]// 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// `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// 390 audit (tests/mobile-measure.js) of every page, then the walk: menus, sign out, register an app, an invite link, sign out everywhere.import { writeFileSync, readFileSync, existsSync } from 'node:fs';import { dirname, join } from 'node:path';import { fileURLToPath } from 'node:url';const [mode, port, sink, shotDir, tid, cdpPort = '8756'] = process.argv.slice(2);const BASE = `http://127.0.0.1:${port}`, sleep = ms => new Promise(r => setTimeout(r, ms)), J = JSON.stringify;const MEASURE = readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'mobile-measure.js'), 'utf8');const EMAIL = '[email protected]'; // an account of the COPY (real data: apps, connections, notifications); the code goes to the sink fileconst list = await (await fetch(`http://127.0.0.1:${cdpPort}/json/list`)).json();const tgt = list.find(t => t.id === tid);const ws = new WebSocket(tgt.webSocketDebuggerUrl.replace(/ws:\/\/[^/]+/, `ws://127.0.0.1:${cdpPort}`)); await new Promise(r => ws.onopen = r);let id = 0; const pend = new Map(), consoleErrors = [], dialogTexts = [];ws.onmessage = m => { const d = JSON.parse(m.data);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); }else if (d.method === 'Page.javascriptDialogOpening') { dialogTexts.push(d.params.message); send('Page.handleJavaScriptDialog', { accept: true }).catch(() => {}); } // the person presses OKelse if (d.method === 'Runtime.exceptionThrown') consoleErrors.push(J(d.params.exceptionDetails).slice(0, 200));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)); };const send = (method, params = {}) => new Promise((ok, bad) => { const i = ++id; pend.set(i, [ok, bad]); ws.send(J({ id: i, method, params })); });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; };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; };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 }; })()`);const click = async sel => { let r = await rect(sel); if (!r) throw new Error('no ' + sel); await sleep(120); r = await rect(sel); 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 }); };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 }); };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 }); } };const shot = async name => { const r = await send('Page.captureScreenshot', { format: 'png' }); writeFileSync(`${shotDir}/${mode}-${name}.png`, Buffer.from(r.data, 'base64')); };const results = []; const check = (n, ok, d = '') => { results.push([n, !!ok]); console.log((ok ? 'PASS ' : 'FAIL ') + n + (ok ? '' : ' ' + d)); };const hydrated = () => waitFor(`!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1`, 'hydrated');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); };const shows = sel => ev(`(() => { const e = document.querySelector(${J(sel)}); return !!e && e.getBoundingClientRect().width > 0; })()`);const txt = sel => ev(`(document.querySelector(${J(sel)}) || {}).textContent || ''`);const lastCode = () => { const ls = existsSync(sink) ? readFileSync(sink, 'utf8').split('\n').filter(l => l.startsWith(EMAIL + ' ')) : []; return ls.length ? ls.at(-1).split(' ')[1] : null; };const audits = [];async function audit(name, W) {const m = await ev(`window.__W = ${W};` + MEASURE);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 };audits.push(r); console.log('AUDIT', J(r)); await shot(`${W}-${name.replace(/[^a-z0-9]+/gi, '-')}`);}// THE SIGN-IN: email typed, "Send me a code" clicked, the code read from the sink like a person reads mail, typed, "Sign in" clickedasync function signIn(W) {await go('/', '#emailform');await typeInto('#email', EMAIL); const before = lastCode();await click('#sendcode'); await waitFor(`location.pathname === '/code' && !!document.querySelector('#code')`, 'code page'); await hydrated();for (let i = 0; i < 40 && lastCode() === before; i++) await sleep(250);const c = lastCode(); check(`${W}: the sink got a 6-digit code`, /^\d{6}$/.test(c || ''), String(c));if (W) await audit('code-page', W);await typeInto('#code', c); await click('#verify');return await waitFor(`!!document.querySelector('#meemail')`, 'signed in');}await send('Page.enable'); await send('Runtime.enable'); await send('DOM.enable'); await send('Network.enable');await send('Target.activateTarget', { targetId: tid }).catch(() => {});await send('Page.bringToFront');await send('Storage.clearDataForOrigin', { origin: BASE, storageTypes: 'service_workers,cache_storage,local_storage' }).catch(() => {});await send('Network.deleteCookies', { name: 'identsid', url: BASE }).catch(() => {});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); };const menuOpen = async (btn, pop) => { await click(btn); await waitFor(`document.querySelector(${J(pop)}).matches(':popover-open')`, pop + ' open'); await sleep(300); };const esc = async () => { await key('Escape', 'Escape', 27); await sleep(300); };try {for (const W of [390, 1280]) {await view(W); const T = `${W}-`;// ---- signed out -------------------------------------------------------------------------------------------------------await go('/', '#emailform'); await audit('signin', W);await go('/start', '#start'); await audit('start', W);await send('Page.navigate', { url: BASE + '/login?app=x&return=http://127.0.0.1:1/cb' }); await waitFor(`!!document.querySelector('#identerror')`, 'error page'); await sleep(400); await audit('login-error', W);await go('/apps', '#signinfirst'); await audit('apps-signed-out', W);// ---- the real sign-in --------------------------------------------------------------------------------------------------const ok = await signIn(W); check(`${T}sign-in with a code from the sink lands on the identities page`, ok && (await txt('#meemail')) === EMAIL, await txt('#meemail'));// the shell must show the signed-in header right after the IN-PLACE sign-in (no navigation, no reload since the click on "Sign in")if (mode === 'new') {check(`${T}right after the in-place sign-in the header has the user menu and the main menu (no reload)`, await ev(`!!document.querySelector('application-header button.user-toggle') && !!document.querySelector('application-header main-menu a[href="/apps"]')`));check(`${T}#whoami shows the address right after the in-place sign-in`, (await txt('#whoami')) === EMAIL, await txt('#whoami'));await waitFor(`!!document.querySelector('main-menu a.current[href="/"]')`, 'current mark', 5000);check(`${T}the main menu marks Identities as the current page (set by the shell's probe ~0.5 s after the page is up)`, await ev(`!!document.querySelector('main-menu a.current[href="/"]')`));}await sleep(500); await audit('identities', W);await click('#newidentity'); await waitFor(`!!document.querySelector('#identityform')`, 'form'); await sleep(400); await audit('identity-form', W);await click('#cancel'); await sleep(300);await go('/apps', '#appssection'); await audit('apps', W);await go('/inbox', '#inboxsection'); await audit('inbox', W);const cid = await ev(`(() => { const a = document.querySelector('#conns a.conn'); return a ? a.getAttribute('href') : null; })()`);if (cid) { await go(cid, '#kindssection, #notfound'); await audit('app-settings', W); } else console.log(' (no connection in this copy)');// ---- menus (new shell only: the old header had three plain links) -------------------------------------------------------await go('/', '#identities');if (mode === 'new') {if (W === 390) {await menuOpen('button.menu-toggle', '#sidebar'); check(`${T}sidebar opens with the main menu ${J(await ev(`[...document.querySelectorAll('#sidebar main-menu a')].map(a => a.textContent)`))}`, (await ev(`document.querySelectorAll('#sidebar main-menu a').length`)) === 3); await shot(`${T}sidebar`);await click('#sidebar main-menu a[href="/apps"]'); await waitFor(`location.pathname === '/apps' && !!document.querySelector('#appssection')`, 'apps via sidebar'); await hydrated(); await waitFor(`!!document.querySelector('#sidebar main-menu a.current[href="/apps"]')`, 'current mark', 5000);check(`${T}a tap on "Apps" in the sidebar opens /apps and the menu marks it`, (await ev(`location.pathname`)) === '/apps' && (await ev(`!!document.querySelector('#sidebar main-menu a.current[href="/apps"]')`)));} else {await click('application-header main-menu a[href="/inbox"]'); await waitFor(`location.pathname === '/inbox' && !!document.querySelector('#inboxsection')`, 'inbox via header'); await hydrated();check(`${T}the header's main menu opens /inbox and marks it`, await ev(`!!document.querySelector('application-header main-menu a.current[href="/inbox"]')`));}await menuOpen('button.user-toggle', '#user-menu'); check(`${T}user menu opens: ${J(await txt('#whoami'))}, Sign out shown`, (await txt('#whoami')) === EMAIL && await shows('#menusignout')); await shot(`${T}user-menu`); await esc();check(`${T}Escape closes the user menu`, !(await ev(`document.querySelector('#user-menu').matches(':popover-open')`)));}// ---- register an app (real typing), its secret once, an invite for it -------------------------------------------------------await go('/apps', '#newapp'); await click('#newapp'); await waitFor(`!!document.querySelector('#appform')`, 'app form');const appName = `E2E ${mode} ${W}`;await typeInto('#fappname', appName); await typeInto('#forigins', `http://127.0.0.1:${port}`); await shot(`${T}app-form`); await click('#saveapp');await waitFor(`!!document.querySelector('#secret')`, 'secret shown'); const secret = await txt('#secret');check(`${T}app registered; the secret is shown once (${secret.slice(0, 3)}…)`, /^sk_[0-9a-f]{48}$/.test(secret)); await sleep(300); await audit('apps-secret', W);await click('#secretdone'); await sleep(300);const appKey = await ev(`(() => { const l = [...document.querySelectorAll('#apps li')].find(li => li.textContent.includes(${J(appName)})); const m = l && l.textContent.match(/pk_[0-9a-f]+/); return m ? m[0] : null; })()`);check(`${T}the app is listed with its key`, !!appKey, appKey);const inv = await (await fetch(`${BASE}/api/invites`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ key: appKey, secret, project: 'demo', role: 'member', return: `http://127.0.0.1:${port}/back` }) })).json();check(`${T}the app made an invite link`, !!inv.url, J(inv));if (inv.url) {const path = new URL(inv.url).pathname;await send('Page.navigate', { url: BASE + path }); await waitFor(`location.pathname.startsWith('/signin/') && !!document.querySelector('#apprequest')`, 'invite page'); await hydrated(); await sleep(500);check(`${T}the invite link opens the identity choice: ${J(await txt('#apprequest'))}`, (await txt('#apprequest')).includes('invited') && (await shows('#chooselist')) , await ev(`location.href`));await audit('invite-choose', W);}// ---- sign out (real click), sign in again, sign out everywhere ---------------------------------------------------------------await go('/', '#identities'); await click('#signout'); if (!await waitFor(`!!document.querySelector('#emailform')`, 'signed out', 8000)) console.log(' DEBUG after #signout:', await ev(`location.href + ' | msg=' + document.querySelector('#message')?.textContent + ' | signout rect=' + JSON.stringify(document.querySelector('#signout')?.getBoundingClientRect()) + ' | top=' + document.elementFromPoint(window.innerWidth/2, 100)?.outerHTML.slice(0,100)`));check(`${T}"Sign out" returns to the sign-in form`, await shows('#emailform')); await shot(`${T}signed-out`);if (!(await signIn(0))) throw new Error('second sign-in failed');if (mode === 'new') { await menuOpen('button.user-toggle', '#user-menu'); await click('#menusignout'); await waitFor(`location.pathname === '/' && !!document.querySelector('#emailform')`, 'user-menu sign out'); check(`${T}user menu "Sign out" signs out`, await shows('#emailform')); if (!(await signIn(0))) throw new Error('third sign-in failed'); }await click('#signoutall'); await waitFor(`!!document.querySelector('#emailform')`, 'signed out everywhere');check(`${T}"Sign out everywhere" (confirm accepted: ${J(dialogTexts.at(-1))}) returns to the sign-in form`, await shows('#emailform') && /every device/.test(dialogTexts.at(-1) || '')); await shot(`${T}signed-out-all`);}const badAudits = audits.filter(a => (a.W === 390 && a.tapsSmall) || a.wide || a.scrollWidth > a.W || a.inputsSmall);const s = (f) => audits.filter(f).reduce((n, a) => n + a.tapsSmall, 0);console.log(`\nSUMMARY ${mode}: audits ${audits.length}, at 390 taps<44 total ${s(a => a.W === 390)}, wider-than-screen ${audits.filter(a => a.W === 390).reduce((n, a) => n + a.wide, 0)}, inputs<16 ${audits.filter(a => a.W === 390).reduce((n, a) => n + a.inputsSmall, 0)}, text<14 ${audits.filter(a => a.W === 390).reduce((n, a) => n + a.textSmall, 0)}; checks ${results.filter(r => r[1]).length}/${results.length}; console errors ${consoleErrors.length}`);for (const e of consoleErrors.slice(0, 6)) console.log(' CONSOLE', e);writeFileSync(`${shotDir}/${mode}-audits.json`, J(audits, null, 1));} catch (e) { console.log('E2E ERROR', e.stack || e); console.log(' PAGE:', await ev(`location.href + ' :: ' + document.body.innerText.slice(0, 300)`).catch(() => '?')); process.exitCode = 1; }await send('Emulation.clearDeviceMetricsOverride'); await send('Emulation.setTouchEmulationEnabled', { enabled: false });await send('Network.deleteCookies', { name: 'identsid', url: BASE }).catch(() => {});await send('Page.navigate', { url: 'about:blank' }); await sleep(300);ws.close(); process.exit(process.exitCode || 0);
Branches
Latest commits
- 443291d4ident mission 012: /start on its own shell (no account), browser gate 152/0, reportmre
- 021dd0fcident mission 012: browser gate waits cold start (IDENT_COLD_MS), header selectors, e2e checks; shell events from a page do not reach it (probe), current not marked, account-bar link 44 pxmre
- 97f77b07ident mission 012 (WIP): onto the layouts theme dbe3de7, shell on AppHeader/MainMenu/UserMenu/Sidebar + ContentFirst, styles cut, check-theme gatemre
- 8e4f435bpaths: projects moved into /media/STORAGE/projects/WorldAPI/mre
- fa288f63ident mission 011: report wording (Intl zone names)mre
- 961fae01ident mission 011: report, LOG, STATUSmre
- 65348039ident#7: delivery gate — console check split at the gate's own server restart (49 checks)mre
- dfa7b783ident#7: README (Delivery, env, gate, files, data), deploy.sh runs tests/delivery.mjsmre
- ab6331f4ident#7: tests/delivery.mjs — fake clock gate: Vienna/New York/Tokyo/UTC 17:00, urgent, mail off, restart, DST days, zone changemre
- 7869f57bident#7: delivery — the daily mail at 17:00 in the user's zone (digests table, once per local day, test clock IDENT_TEST_CLOCK), urgent mailed at once, push hookmre
- 371ef1b5ident#7: lib/mail.hl sendNotificationMail (sink: <sink>.mail, one JSON line per mail)mre
- 39749e0bident#7: time zones through hl:time — server checks isZone, an account without a known zone reads as UTC, allAccountsmre
- 7a54fe72mission brief 011mre
- a6a874cdident mission 010: vendor hybriel 0f396652 (plugins + compose cache volume/tmpfs + deploy URL wait + report)mre
- 4e7cf78emission brief 010mre
- e8b2b0f7docker-compose: init: true (hybriel#156, PID 1 ignored SIGTERM, every restart waited 10 s)mre
- 5fdbb6b2ident mission 009: report — scratch folder notemre
- 74235815ident mission 009 (4/4): docs (README files map + same-output test, STATUS, LOG), report, tests/letcount.py + realdata-baseline/comparemre
- fe183516ident mission 009 (3/4): let only where reassigned — 293 never-reassigned lets are plain declarations; kept: reassigned, loop bodies, names of a file member, a name declared twice in one function; same outputmre
- d2e7f91bident mission 009 (2/4): one lib file per topic (login, accounts, identities, apps, invites, selector, notify + helpers, util), function routes as thin wrappers in lib/api.hl, project.hl = the map; same outputmre