gitoria

notes

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit542a0383542a0383notes mission 015: e2e-chrome E2E_HOST (own cookie jar in the shared Chrome)mre542a0383/tests/e2e-roundtrip.mjs

8.3 KB

  1. // tests/e2e-roundtrip.mjs (mission 010): the stored notes round-trip through the MdEditor block, on a COPY of a deploy backup.
  2. // node tests/e2e-roundtrip.mjs <backup.tgz> <port> <chrome-from>-<chrome-to>
  3. // For EVERY live note of the copy (a session of the creator is written into the copy): open it in real headless Chrome and
  4. // 1. OPEN: the editor's hidden field holds the stored Markdown byte for byte (nothing was touched, nothing is saved);
  5. // 2. EDIT + SAVE: real mouse click into the first paragraph / heading / list item, End, type "x", Backspace — the Markdown
  6. // after the edit is read back and the server's stored text after the save too: both must equal the stored text (an
  7. // unchanged table is written back byte for byte, also when the text around it changes — block README "Tables").
  8. // Notes whose Markdown the block writes in its canonical form instead (a changed block is canonical: `*em*`, `- item`) are
  9. // listed with the first differing line — that is a finding, not hidden. Kills only what it started; deletes the copy.
  10. import { spawn, execFileSync } from 'node:child_process';
  11. import { writeFileSync, mkdirSync, rmSync, existsSync } from 'node:fs';
  12. import { createHash, randomBytes } from 'node:crypto';
  13. import { join, resolve, dirname } from 'node:path';
  14. import { fileURLToPath } from 'node:url';
  15. import { launchBrowser } from './cdp.mjs';
  16. const [tgz, portArg, chromeArg] = process.argv.slice(2);
  17. const APP = resolve(dirname(fileURLToPath(import.meta.url)), '..');
  18. const PORT = Number(portArg);
  19. const [CH_FROM, CH_TO] = (chromeArg || '8756-8759').split('-').map(Number);
  20. const BASE = `http://notes.test:${PORT}`, API = `http://127.0.0.1:${PORT}`;
  21. const W = join(APP, '.scratch/e2e-roundtrip');
  22. const USER = '0muh6o5a3kkd';
  23. if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';
  24. process.env.HL_CHROME_ARGS = `--host-resolver-rules=MAP notes.test 127.0.0.1|--unsafely-treat-insecure-origin-as-secure=${BASE}`;
  25. rmSync(W, { recursive: true, force: true });
  26. mkdirSync(join(W, 'data'), { recursive: true }); mkdirSync(join(W, 'sessions'), { recursive: true });
  27. execFileSync('tar', ['-xzf', resolve(tgz), '-C', join(W, 'data'), 'storage/mpackdb']);
  28. const sid = randomBytes(16).toString('hex');
  29. const now = Date.now();
  30. writeFileSync(join(W, 'sessions', createHash('sha256').update(sid).digest('hex')),
  31. JSON.stringify({ created: now, data: { tag: 'rt' }, handled: [], id: sid, seen: now, user: { id: USER } }), { mode: 0o600 });
  32. const COOKIE = 'notessid=' + sid;
  33. let failures = 0, passes = 0;
  34. const check = (label, ok, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`); if (ok) passes++; else failures++; };
  35. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  36. const J = JSON.stringify;
  37. let log = '';
  38. const srv = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'],
  39. env: { ...process.env, NOTES_PORT: String(PORT), NOTES_PUBLIC_URL: BASE, NOTES_STORAGE: join(W, 'data/storage/mpackdb'),
  40. NOTES_SESSIONS: join(W, 'sessions') + '/', NOTES_WATCH: '0', IDENT_URL: 'http://ident.test', IDENT_API_KEY: 'pk_rt', IDENT_API_SECRET: 'sk_rt' } });
  41. srv.stdout.on('data', d => log += d); srv.stderr.on('data', d => log += d);
  42. let b = null;
  43. const api = async (path) => (await fetch(API + path, { headers: { cookie: COOKIE } })).json();
  44. // the list has no text: every note is read by id
  45. const 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; };
  46. 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'; };
  47. try {
  48. for (let i = 0; i < 480; i++) { try { if ((await fetch(API + '/')).ok) break; } catch {} await sleep(250); }
  49. check('the session is the creator', (await api('/api/me')).user === USER);
  50. const before = await alive();
  51. const withTable = before.filter(n => /^\s*\|.*\|\s*$/m.test(n.text) && /^\s*\|?\s*:?-{2,}/m.test(n.text));
  52. console.log(`live notes in the copy: ${before.length}, with a table: ${withTable.length}`);
  53. b = await launchBrowser({ debugPortRange: [CH_FROM, CH_TO] });
  54. const p = await b.newPage();
  55. await p.send('Network.enable');
  56. await p.send('Network.setCookie', { name: 'notessid', value: sid, url: BASE + '/' });
  57. await p.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  58. const val = () => p.evaluate(`(document.querySelector('#notetext input[name=text]') || {}).value`);
  59. 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 }); };
  60. const canon = [], tableBad = [], skipped = [], openBad = [];
  61. for (const n of before.slice().sort((x, y) => x.id < y.id ? -1 : 1)) {
  62. await p.goto(BASE + '/note/' + n.id);
  63. await p.waitFor(`!!window.__hl && !!document.querySelector('md-editor article > *')`, { timeout: 60000 });
  64. await sleep(400);
  65. const opened = await val();
  66. if (opened !== n.text) openBad.push(n.id + ' ' + firstDiff(n.text, opened || ''));
  67. // the first block that is not a table: click it, End, "x", Backspace
  68. const 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`;
  69. 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) }; })()`);
  70. if (!bx) { skipped.push(n.id); continue; }
  71. 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 });
  72. await key('End', 'End', 35);
  73. await p.send('Input.dispatchKeyEvent', { type: 'keyDown', text: 'x', unmodifiedText: 'x', key: 'x' }); await p.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'x' });
  74. await sleep(150);
  75. const typed = await val();
  76. await key('Backspace', 'Backspace', 8);
  77. await sleep(1800); // the page sends what was typed 0.6 s ago (its 1 s tick)
  78. const after = await val();
  79. const stored = (await alive()).find(x => x.id === n.id);
  80. const hasTable = withTable.some(t => t.id === n.id);
  81. const same = after === n.text && stored && stored.text === n.text;
  82. if (!same) (hasTable ? tableBad : canon).push(n.id + ' ' + firstDiff(n.text, after || '') + (stored && stored.text !== after ? ' [server differs from editor]' : ''));
  83. if (typed === n.text) openBad.push(n.id + ' typing "x" changed nothing');
  84. }
  85. console.log(`edited ${before.length - skipped.length} notes, skipped (only a table / empty): ${skipped.length}`);
  86. check(`OPEN: all ${before.length} stored notes read back from the editor byte for byte`, openBad.length === 0, openBad.slice(0, 5).join(' | '));
  87. 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(' | '));
  88. 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);
  89. const now2 = await alive();
  90. check('no note was added or lost', now2.length === before.length, `${before.length} → ${now2.length}`);
  91. check('the server logged no error', !/error|Error/.test(log.replace(/error absorbed/g, '')), log.slice(-400));
  92. } catch (e) {
  93. console.log('FAIL crashed — ' + (e && e.stack || e)); failures++; console.log(log.slice(-1000));
  94. } finally {
  95. if (b) { try { await b.close(); } catch {} }
  96. try { srv.kill('SIGTERM'); } catch {}
  97. await sleep(1000);
  98. rmSync(W, { recursive: true, force: true });
  99. console.log(`${passes} passed, ${failures} failed (copy deleted: ${!existsSync(W)})`);
  100. process.exit(failures ? 1 : 0);
  101. }

Branches

Latest commits

  • 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
  • 447da53dnotes mission 014: report — remaining gates and lisbeth E2E proofmre
  • fd9f92c3notes mission 014: report (partial), LOG, STATUSmre
  • b2501360notes mission 014: open() sets asking=false before flush(0) (hybriel#196)mre
  • 9414ce59notes mission 014: merge theme 76f99f6, components 3794c59, strict single-press openAsk (fails on old open())mre
  • c08c655anotes 013: theme re-copied from layouts 76f99f6 (menu marks the current page), current = true on the menu item, e2e marker checks, reportmre
  • 21c8f65dnotes mission 012: STATUSmre
  • 0bbb3dd9notes mission 012: delete section of the browser gate de-flaked (openAsk: calm wait, press again when the question closes by itself); report 012mre
  • f431bdf8notes mission 011: notes on the layouts theme (ListFirst shell), styles cut, check-theme gate, E2E extended; reportmre
  • 1a8603d1notes mission 011 WIP: deploy.sh gate summary also matches check-theme, browser.mjs logout via the user menumre
  • dae2e508notes mission 011 WIP: theme dbe3de7, shell on AppHeader/MainMenu/UserMenu/Sidebar + ListFirst, styles cut to the app's own, check-theme gate, e2e auditmre
  • fd36da27notes mission 010: the note editor is the Hybriel MdEditor block (components.hybriel 1442e58, verbatim); md-editor.js, its route, script tag and offlineFiles retired; gate 66/0, realdata-offline 12/0, round-trip and Chrome E2E tests; report 010mre
  • efa92170notes tests/identkit.mjs: refuse a taken ident port, cold-wait deadline, emit, identities; mission 009 reportmre
  • f3dec0f1Merge branch 'w7'mre
  • d1cf966dre-vendor hybriel 97bcf128: offlineFiles for the editor script, 44 px taps, 390 px offline checks, mission 008mre
  • 4a610a21paths: projects moved into /media/STORAGE/projects/WorldAPI/mre
  • eeaea980report 007: say which runs included the removed checkmre
  • 8a8ad9banotes mission 007: report, LOG, STATUSmre