notes
All repositories: gitoria
8.3 KB
// tests/e2e-roundtrip.mjs (mission 010): the stored notes round-trip through the MdEditor block, on a COPY of a deploy backup.// node tests/e2e-roundtrip.mjs <backup.tgz> <port> <chrome-from>-<chrome-to>// For EVERY live note of the copy (a session of the creator is written into the copy): open it in real headless Chrome and// 1. OPEN: the editor's hidden field holds the stored Markdown byte for byte (nothing was touched, nothing is saved);// 2. EDIT + SAVE: real mouse click into the first paragraph / heading / list item, End, type "x", Backspace — the Markdown// after the edit is read back and the server's stored text after the save too: both must equal the stored text (an// unchanged table is written back byte for byte, also when the text around it changes — block README "Tables").// Notes whose Markdown the block writes in its canonical form instead (a changed block is canonical: `*em*`, `- item`) are// listed with the first differing line — that is a finding, not hidden. Kills only what it started; deletes the copy.import { spawn, execFileSync } from 'node:child_process';import { writeFileSync, mkdirSync, rmSync, existsSync } from 'node:fs';import { createHash, randomBytes } from 'node:crypto';import { join, resolve, dirname } from 'node:path';import { fileURLToPath } from 'node:url';import { launchBrowser } from './cdp.mjs';const [tgz, portArg, chromeArg] = process.argv.slice(2);const APP = resolve(dirname(fileURLToPath(import.meta.url)), '..');const PORT = Number(portArg);const [CH_FROM, CH_TO] = (chromeArg || '8756-8759').split('-').map(Number);const BASE = `http://notes.test:${PORT}`, API = `http://127.0.0.1:${PORT}`;const W = join(APP, '.scratch/e2e-roundtrip');const USER = '0muh6o5a3kkd';if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';process.env.HL_CHROME_ARGS = `--host-resolver-rules=MAP notes.test 127.0.0.1|--unsafely-treat-insecure-origin-as-secure=${BASE}`;rmSync(W, { recursive: true, force: true });mkdirSync(join(W, 'data'), { recursive: true }); mkdirSync(join(W, 'sessions'), { recursive: true });execFileSync('tar', ['-xzf', resolve(tgz), '-C', join(W, 'data'), 'storage/mpackdb']);const sid = randomBytes(16).toString('hex');const now = Date.now();writeFileSync(join(W, 'sessions', createHash('sha256').update(sid).digest('hex')),JSON.stringify({ created: now, data: { tag: 'rt' }, handled: [], id: sid, seen: now, user: { id: USER } }), { mode: 0o600 });const COOKIE = 'notessid=' + sid;let failures = 0, passes = 0;const check = (label, ok, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`); if (ok) passes++; else failures++; };const sleep = (ms) => new Promise(r => setTimeout(r, ms));const J = JSON.stringify;let log = '';const srv = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'],env: { ...process.env, NOTES_PORT: String(PORT), NOTES_PUBLIC_URL: BASE, NOTES_STORAGE: join(W, 'data/storage/mpackdb'),NOTES_SESSIONS: join(W, 'sessions') + '/', NOTES_WATCH: '0', IDENT_URL: 'http://ident.test', IDENT_API_KEY: 'pk_rt', IDENT_API_SECRET: 'sk_rt' } });srv.stdout.on('data', d => log += d); srv.stderr.on('data', d => log += d);let b = null;const api = async (path) => (await fetch(API + path, { headers: { cookie: COOKIE } })).json();// the list has no text: every note is read by idconst alive = async () => { const out = []; for (const n of (await api('/api/notes')).notes.filter(n => !n.gone)) out.push({ ...n, text: (await api('/api/notes?id=' + n.id)).text }); return out; };const firstDiff = (a, c) => { const x = a.split('\n'), y = c.split('\n'); for (let i = 0; i < Math.max(x.length, y.length); i++) if (x[i] !== y[i]) return `line ${i + 1}: ${J(x[i])} → ${J(y[i])}`; return 'same lines, differs in line ends'; };try {for (let i = 0; i < 480; i++) { try { if ((await fetch(API + '/')).ok) break; } catch {} await sleep(250); }check('the session is the creator', (await api('/api/me')).user === USER);const before = await alive();const withTable = before.filter(n => /^\s*\|.*\|\s*$/m.test(n.text) && /^\s*\|?\s*:?-{2,}/m.test(n.text));console.log(`live notes in the copy: ${before.length}, with a table: ${withTable.length}`);b = await launchBrowser({ debugPortRange: [CH_FROM, CH_TO] });const p = await b.newPage();await p.send('Network.enable');await p.send('Network.setCookie', { name: 'notessid', value: sid, url: BASE + '/' });await p.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });const val = () => p.evaluate(`(document.querySelector('#notetext input[name=text]') || {}).value`);const key = async (k, code, vk, mods = 0) => { await p.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', modifiers: mods, key: k, code, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk }); await p.send('Input.dispatchKeyEvent', { type: 'keyUp', modifiers: mods, key: k, code, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk }); };const canon = [], tableBad = [], skipped = [], openBad = [];for (const n of before.slice().sort((x, y) => x.id < y.id ? -1 : 1)) {await p.goto(BASE + '/note/' + n.id);await p.waitFor(`!!window.__hl && !!document.querySelector('md-editor article > *')`, { timeout: 60000 });await sleep(400);const opened = await val();if (opened !== n.text) openBad.push(n.id + ' ' + firstDiff(n.text, opened || ''));// the first block that is not a table: click it, End, "x", Backspaceconst sel = `md-editor article > p, md-editor article > h1, md-editor article > h2, md-editor article > h3, md-editor article > h4, md-editor article > h5, md-editor article > h6, md-editor article > ul > li, md-editor article > ol > li`;const bx = await p.evaluate(`(() => { const e = document.querySelector(${J(sel)}); if (!e) return null; e.scrollIntoView({ block: 'center' }); const r = e.getBoundingClientRect(); return { x: Math.round(r.left + 8), y: Math.round(r.top + r.height / 2) }; })()`);if (!bx) { skipped.push(n.id); continue; }for (const [type, buttons] of [['mouseMoved', 0], ['mousePressed', 1], ['mouseReleased', 0]]) await p.send('Input.dispatchMouseEvent', { type, x: bx.x, y: bx.y, button: 'left', clickCount: 1, buttons });await key('End', 'End', 35);await p.send('Input.dispatchKeyEvent', { type: 'keyDown', text: 'x', unmodifiedText: 'x', key: 'x' }); await p.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'x' });await sleep(150);const typed = await val();await key('Backspace', 'Backspace', 8);await sleep(1800); // the page sends what was typed 0.6 s ago (its 1 s tick)const after = await val();const stored = (await alive()).find(x => x.id === n.id);const hasTable = withTable.some(t => t.id === n.id);const same = after === n.text && stored && stored.text === n.text;if (!same) (hasTable ? tableBad : canon).push(n.id + ' ' + firstDiff(n.text, after || '') + (stored && stored.text !== after ? ' [server differs from editor]' : ''));if (typed === n.text) openBad.push(n.id + ' typing "x" changed nothing');}console.log(`edited ${before.length - skipped.length} notes, skipped (only a table / empty): ${skipped.length}`);check(`OPEN: all ${before.length} stored notes read back from the editor byte for byte`, openBad.length === 0, openBad.slice(0, 5).join(' | '));check(`EDIT + SAVE: all ${withTable.length} notes with a table stay byte-identical (editor and server) after an edit next to the table`, tableBad.length === 0, tableBad.slice(0, 5).join(' | '));console.log(`FINDING — notes without a table that the block wrote in its canonical form after an edit: ${canon.length}`); for (const c of canon) console.log(' ' + c);const now2 = await alive();check('no note was added or lost', now2.length === before.length, `${before.length} → ${now2.length}`);check('the server logged no error', !/error|Error/.test(log.replace(/error absorbed/g, '')), log.slice(-400));} catch (e) {console.log('FAIL crashed — ' + (e && e.stack || e)); failures++; console.log(log.slice(-1000));} finally {if (b) { try { await b.close(); } catch {} }try { srv.kill('SIGTERM'); } catch {}await sleep(1000);rmSync(W, { recursive: true, force: true });console.log(`${passes} passed, ${failures} failed (copy deleted: ${!existsSync(W)})`);process.exit(failures ? 1 : 0);}
Branches
Latest commits
- 72bd4f83notes mobile: list header on the gutter, delete confirmation as a question + two equal buttons, Delete note under the editor edgemre
- ba1e73f8notes: a sent edit is done once the server's version is not older, so a second writer's text shows in the first tab; gate: two writers both waysmre
- c69ef9ebsync components.hybriel 134b4e3: MdEditor builds an editor put into the page at once, redraws a surface put in anew (F5, hybriel#211)mre
- 2eb783f5sync components 9a: shared Icon (icons/icons.hl), md-editor toolbar icons + single focus ring (components f4-icons ba96735)mre
- 4dd46dadsync-components: copy icons/icons.hl + README (F4); testsmre
- c92e4a0ftests/e2e-outside.mjs: real-Chrome E2E, a note pushed from another device while open, then typingmre
- 0516b4ccmd-editor.hl: verbatim copy of components f3-mdvalue (an older text handed back is kept)mre
- 38cc11ecmd-editor.hl: verbatim copy of components f3-mdvalue (an outside value change is shown by the editor)mre
- 3e7e79f5reports/H1-hydrate.mdmre
- d98775e8tests/browser.mjs: wait for hydration before the clicks after a goto('/') (tables new note, phone sidebar)mre
- 1f3198b6tests/cdp.mjs: HL_CPU_THROTTLE=<rate> optional CPU throttling for gate runsmre
- 39cf9fdfre-vendor Hybriel 5406d146 (hl:web batches 9+10: #72 emits while the socket is closed delivered after reconnect, browser boot linear, faster list appends; contains int 6–14 + m406)mre
- db07aa84tests: short-id-switch ports from env (NOTES_SWITCH_IDENT_PORT/_PORT), defaults unchangedmre
- ef9f9feere-vendor Hybriel 6f8a0689 (int 6–11: streaming cursors, #203 index heal + close() fix, fd403 listDir/cursor fds, hl:time browser side, hl:web batches 5+6)mre
- 5485467cdocker-compose: nofile 65536 (Hybriel int 6+ boot opened >1024 files in the tracker)mre
- 86ea4a85deploy: backup copies index files first and *.mpack data last (hot-copy skew, hybriel #203)mre
- edeab20fnotes mission 015: mission, report, LOG, STATUSmre
- 542a0383notes mission 015: e2e-chrome E2E_HOST (own cookie jar in the shared Chrome)mre
- 8b30f510notes mission 015: main-menu from layouts 0bcc629, current = true kept (route marks only /), server-HTML marker checksmre
- 84b574c4notes mission 015: re-vendor plugins from hybriel f9614007 (incl. web, #117)mre