gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmainfe209ffeMerge branch 'w56-owner-members' into mainGitoriamain/tests/e2e-real.mjs

16.5 KB

  1. import { requiredPort } from './gate-ports.mjs';
  2. // tests/e2e-real.mjs — the gitoria walk in a REAL browser (an existing tab of lisbeth's test Chrome, over the CDP tunnel), not a gate:
  3. // prints numbers and writes screenshots. Own ident + gitoria on a throw-away store (ports from the env), the tab reaches them through
  4. // `ssh -R <port>:127.0.0.1:<port> lisbeth` as http://gitoria.localhost:<port> (*.localhost is loopback in Chrome, no resolver rule).
  5. // E2E_APP=<app dir> E2E_PORT=8742 E2E_IDENT_PORT=8743 E2E_TAG=old|new E2E_SHOTS=<dir> E2E_CDP=http://127.0.0.1:9223 E2E_TAB=<target id>
  6. // node tests/e2e-real.mjs
  7. import { spawn, execFileSync } from 'node:child_process';
  8. import { rmSync, mkdirSync, writeFileSync, readFileSync } from 'node:fs';
  9. import { dirname, join, resolve } from 'node:path';
  10. import { fileURLToPath } from 'node:url';
  11. import { launchBrowser, Page } from './cdp.mjs';
  12. import { startIdent } from './identkit.mjs';
  13. const HERE = dirname(fileURLToPath(import.meta.url));
  14. const APP = resolve(process.env.E2E_APP || join(HERE, '..'));
  15. const PORT = requiredPort('E2E_PORT'), IPORT = requiredPort('E2E_IDENT_PORT');
  16. const TAG = process.env.E2E_TAG || 'x', SHOTS = process.env.E2E_SHOTS, TAB = process.env.E2E_TAB;
  17. const STORE = join(process.env.E2E_STORE, TAG);
  18. const BASE = `http://gitoria.localhost:${PORT}`, REPO = (s) => `http://${s}.gitoria.localhost:${PORT}`, IDENT_B = `http://ident.gitoria.localhost:${IPORT}`;
  19. const IDENT_DIR = process.env.GITORIA_GATE_IDENT_DIR || '/media/STORAGE/projects/WorldAPI/ident.worldapi.org';
  20. const MEASURE = readFileSync(join(HERE, 'mobile-measure.js'), 'utf8');
  21. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  22. const J = JSON.stringify;
  23. mkdirSync(SHOTS, { recursive: true }); rmSync(STORE, { recursive: true, force: true }); mkdirSync(STORE, { recursive: true });
  24. process.env.HL_CDP_URL = process.env.E2E_CDP || 'http://127.0.0.1:9223';
  25. let browserConn = null; let ident = null, server = null, page = null, slog = () => ''; const results = [];
  26. const noise = /ERR_|Failed to load resource|WebSocket connection/;
  27. const seen = new Set();
  28. const report = (where) => { for (const m of page.messages) { if ((m.level === 'error' || m.level === 'warning') && !noise.test(m.text) && !seen.has(m)) { seen.add(m); console.log('CONSOLE ERROR at', where, '|', m.text.split('\n')[0].slice(0, 160)); } } };
  29. const hydrated = () => page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { label: 'hydrated', timeout: 30000 });
  30. const shows = (sel) => page.evaluate(`(() => { const e = document.querySelector(${J(sel)}); return !!e && e.getBoundingClientRect().width > 0; })()`);
  31. async function view(w) {
  32. if (w < 600) { await page.send('Emulation.setDeviceMetricsOverride', { width: w, height: 844, deviceScaleFactor: 2, mobile: true }); await page.send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 5 }); }
  33. else { await page.send('Emulation.setTouchEmulationEnabled', { enabled: false }); await page.send('Emulation.setDeviceMetricsOverride', { width: w, height: 900, deviceScaleFactor: 1, mobile: false }); }
  34. await sleep(300);
  35. }
  36. async function shot(name) { const { data } = await page.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(SHOTS, `${TAG}-${name}.png`), Buffer.from(data, 'base64')); }
  37. async function measure(name, w) {
  38. await hydrated(); await sleep(500);
  39. await page.evaluate(`window.__ev = []; document.addEventListener('pointerdown', e => window.__ev.push('pd:' + e.pointerType + ':' + e.target.tagName), true); document.addEventListener('click', e => window.__ev.push('click:' + e.target.tagName), true); 1`);
  40. const m = await page.evaluate(`window.__W = ${w};` + MEASURE);
  41. report(name + ' (after load)');
  42. const r = { name, w, scrollWidth: m.docScrollWidth, tapsSmall: m.tapsSmall, taps: m.taps, smallList: (m.tapsSmallList || []).slice(0, 6), inputsSmall: (m.inputsSmallList || []).length, header: m.headerH, boxesOver: (m.boxesOver || []).length };
  43. results.push(r); console.log(J(r)); await shot(name.replace(/[^a-z0-9]+/gi, '-'));
  44. }
  45. async function go(url, ready) {
  46. await page.goto(url); await page.send('Page.bringToFront'); await page.waitForSelector(ready, { timeout: 30000 }); }
  47. async function toggle(sel, box) {
  48. const open = `!!document.querySelector(${J(box)}) && document.querySelector(${J(box)}).matches(':popover-open')`;
  49. for (let i = 0; i < 4; i++) { // a real tap; when the page was re-rendering under it and nothing opened, tap again (a tap on an open box would close it, so only when closed)
  50. if (await page.evaluate(open)) break;
  51. await page.click(sel); await sleep(1500);
  52. if (i) console.log(' (tap', i + 1, 'for', box + ')');
  53. }
  54. report('tap ' + sel + ' (before it opened)');
  55. await page.waitFor(open, { label: box + ' open', timeout: 5000 }).catch(async (e) => { console.log('DIAG3', await page.evaluate(`(() => { const r = document.querySelector(${J(sel)}).getBoundingClientRect(); const e = document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2); return JSON.stringify({ r: [r.left, r.top, r.width, r.height], at: e && (e.tagName + '.' + (e.className.baseVal ?? e.className)), vis: document.visibilityState, focus: document.hasFocus(), ev: window.__ev }); })()`)); throw e; });
  56. await sleep(300); report('tap ' + sel + ' (after it opened)');
  57. }
  58. // mission 009 (theme 76f99f6): the main menu marks the current page beyond colour — aria-current="page" on exactly one visible link and an
  59. // inset accent bar (box-shadow). gitoria has ONE item (Repositories) and every page is under it (`current = true`), so "the marker moves"
  60. // is shown as: it is on every page, and it is still there after a REAL click on the item itself (to the home page).
  61. const marks = [];
  62. async function mark(name, w) {
  63. const sel = w < 600 ? '#sidebar main-menu a' : 'application-header main-menu a';
  64. const m = await page.evaluate(`(() => { const ls = [...document.querySelectorAll(${J(sel)})].filter(a => a.getBoundingClientRect().width > 0); const cur = ls.filter(a => a.getAttribute('aria-current') === 'page'); const c = cur[0]; const cs = c && getComputedStyle(c); return { links: ls.length, current: cur.length, text: c && c.textContent, cls: c && c.className, shadow: cs && cs.boxShadow, others: ls.filter(a => a.getAttribute('aria-current') !== 'page' && a.getAttribute('aria-current') !== 'false').length }; })()`);
  65. const ok = m.links === 1 && m.current === 1 && m.cls.includes('current') && !!m.shadow && m.shadow !== 'none';
  66. marks.push({ name, ok }); console.log(ok ? 'ok ' : 'FAIL', 'menu marker', name, J(m));
  67. return ok;
  68. }
  69. async function clickMenuItem(w, name) {
  70. const sel = w < 600 ? '#sidebar main-menu a' : 'application-header main-menu a';
  71. await page.click(sel); await page.waitForSelector('#repos li', { timeout: 30000 }); await hydrated();
  72. if (w < 600) { await toggle('button.menu-toggle', '#sidebar'); }
  73. await mark(name + ' (after a click on the item: home)', w);
  74. }
  75. async function walk(w, signedIn) {
  76. await view(w);
  77. const L = (n) => `${w} ${n}${signedIn ? '' : ' (signed out)'}`;
  78. await go(BASE + '/', '#repos li'); await measure(L('home'), w); if (w >= 600) await mark(L('home'), w);
  79. await go(REPO('alpha') + '/', '#reponame'); await measure(L('readme'), w); if (w >= 600) await mark(L('readme'), w);
  80. await go(REPO('alpha') + '/code', '#entries li'); await measure(L('code folder'), w); if (w >= 600) await mark(L('code folder'), w);
  81. await go(REPO('alpha') + '/code/src/a.txt', '#lines li'); await measure(L('file'), w); if (w >= 600) await mark(L('file'), w);
  82. await go(REPO('alpha') + '/commit/' + process.env.E2E_SHA, '#entries li'); await measure(L('commit'), w); if (w >= 600) await mark(L('commit'), w);
  83. await go(REPO('alpha') + '/pulls', 'repo-pulls'); await measure(L('pulls'), w); if (w >= 600) await mark(L('pulls'), w);
  84. if (signedIn) { await go(REPO('alpha') + '/settings', 'repo-settings'); await measure(L('settings'), w); }
  85. if (w < 600) {
  86. await go(REPO('alpha') + '/code', '#entries li'); await hydrated(); await toggle('button.menu-toggle', '#sidebar'); await measure(L('sidebar open'), w); await mark(L('code, sidebar open'), w); await shot('menu-' + w + '-code-sidebar'); await clickMenuItem(w, L('code'));
  87. if (signedIn) { await go(REPO('alpha') + '/', '#reponame'); await hydrated(); await toggle('button.user-toggle', '#user-menu'); await measure(L('user menu open'), w); }
  88. else { await go(REPO('alpha') + '/', '#reponame'); await hydrated(); await measure(L('login in the header'), w); }
  89. } else if (signedIn) {
  90. await go(REPO('alpha') + '/code', '#entries li'); await hydrated(); await clickMenuItem(w, L('code')); await shot('menu-' + w + '-home-after-click');
  91. await go(REPO('alpha') + '/', '#reponame'); await hydrated(); await toggle('button.user-toggle', '#user-menu'); await measure(L('user menu open'), w);
  92. }
  93. }
  94. try {
  95. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IPORT });
  96. const alice = await ident.signIn('[email protected]');
  97. const APPKEY = await ident.registerApp(alice, 'gitoria (e2e)', [BASE]);
  98. server = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'],
  99. env: { ...process.env, GITORIA_PORT: String(PORT), GITORIA_STORAGE: join(STORE, 'mpackdb'), GITORIA_SESSIONS: join(STORE, 'sessions') + '/', GITORIA_WATCH: '0', GITORIA_GIT: join(STORE, 'git'),
  100. GITORIA_PUBLIC_URL: BASE, IDENT_URL: IDENT_B, IDENT_EXCHANGE_URL: ident.base, IDENT_API_KEY: APPKEY.key, IDENT_API_SECRET: APPKEY.secret } });
  101. let log = ''; slog = () => log; server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  102. for (let i = 0; i < 600; i++) { try { if ((await fetch(`http://127.0.0.1:${PORT}/api/repos`)).ok) break; } catch {} await sleep(250); }
  103. // the real tab: an EXISTING page target, attached (never created, never closed)
  104. const b = await launchBrowser(); browserConn = b.conn;
  105. const { sessionId } = await b.conn.send('Target.attachToTarget', { targetId: TAB, flatten: true });
  106. page = new Page(b, TAB, sessionId); await page._init();
  107. await b.conn.send('Target.activateTarget', { targetId: TAB }); // a background tab gets no real input: bring it to the front for the run, give the front back at the end
  108. { const wf = page.waitFor.bind(page); page.waitFor = (e, o = {}) => wf(e, { ...o, timeout: (o.timeout || 10000) * 3 }); const gt = page.goto.bind(page); page.goto = (u, o = {}) => gt(u, { ...o, timeout: (o.timeout || 15000) * 3 }); }
  109. await view(1280);
  110. await page.send('Network.enable');
  111. // earlier runs leave cookies, a service worker and caches for these origins in the shared profile: clear exactly these origins, nothing else
  112. for (const o of [BASE, IDENT_B, REPO('alpha')]) await page.send('Storage.clearDataForOrigin', { origin: o, storageTypes: 'all' });
  113. for (const c of (await page.send('Network.getAllCookies')).cookies.filter(c => /gitoria\.localhost/.test(c.domain))) await page.send('Network.deleteCookies', { name: c.name, domain: c.domain, path: c.path });
  114. const [ck, cv] = alice.cookie.split('=');
  115. await page.send('Network.setCookie', { name: ck, value: cv, url: IDENT_B + '/' });
  116. // sign in by real clicks: login button (ident dropdown on a phone), choose the identity, give a name
  117. await view(390);
  118. await go(BASE + '/', '#repos, #heading'); await hydrated();
  119. await page.evaluate(`window.__t = []; document.querySelector('#ident-panel').addEventListener('toggle', e => window.__t.push(e.newState + '@' + Math.round(performance.now()))); document.addEventListener('pointerdown', e => window.__t.push('pd:' + e.pointerType + ':' + e.target.tagName + '@' + Math.round(performance.now())), true); document.addEventListener('click', e => window.__t.push('click:' + e.target.tagName + '@' + Math.round(performance.now())), true); 1`);
  120. if (!(await shows('#loginbutton'))) await page.click('button.ident-toggle');
  121. await page.waitFor(`(() => { const e = document.querySelector('#loginbutton'); return !!e && e.getBoundingClientRect().width > 0; })()`, { label: 'login button shown' }).catch(async (e) => { await page.click('button.ident-toggle'); await sleep(1500); console.log('after 2nd click open:', await page.evaluate(`document.querySelector('#ident-panel').matches(':popover-open')`), 'toggle rect', J(await page.evaluate(`(() => { const r = document.querySelector('button.ident-toggle').getBoundingClientRect(); const e = document.elementFromPoint(r.left + r.width/2, r.top + r.height/2); return [r.left, r.top, r.width, r.height, e && e.tagName + '.' + e.className, innerWidth, innerHeight, document.hasFocus()]; })()`))); console.log('EVENTS', J(await page.evaluate('window.__t'))); console.log('DIAG', await page.evaluate(`J = JSON.stringify; J({ href: location.href, tog: !!document.querySelector('button.ident-toggle'), panel: !!document.querySelector('#ident-panel'), open: document.querySelector('#ident-panel') && document.querySelector('#ident-panel').matches(':popover-open'), lb: !!document.querySelector('#loginbutton'), w: innerWidth, html: (document.querySelector('ident-menu')||{}).outerHTML })`), page.dumpConsole()); throw e; });
  122. await page.click('#loginbutton');
  123. await page.waitForSelector('#chooselist', { timeout: 30000 }); await hydrated(); await page.click('#chooselist li:nth-child(1) :is(a, button)');
  124. await page.waitForSelector('#nameform', { timeout: 30000 }); await hydrated(); await page.type('#displayname', 'alice'); await page.click('#namesave');
  125. await page.waitFor('!document.querySelector("#nameform")', { label: 'name saved' });
  126. await page.waitForSelector('#createform', { timeout: 30000 }); await hydrated();
  127. await page.type('#slug', 'alpha'); await page.type('#description', 'The first repository'); await page.click('#createsave');
  128. await page.waitFor('/Created .alpha./.test(document.body.innerText)', { label: 'repo alpha created', timeout: 30000 }).catch(async (e) => { console.log('DIAG2', await page.evaluate('location.href + " | " + document.body.innerText.slice(0, 600)'), page.dumpConsole().slice(-800)); throw e; });
  129. const work = join(STORE, 'work'); mkdirSync(work, { recursive: true });
  130. const git = (...a) => execFileSync('git', ['-C', work, '-c', 'user.name=t', '-c', '[email protected]', ...a], { stdio: 'pipe' }).toString();
  131. git('init', '-q', '-b', 'main'); mkdirSync(join(work, 'src'));
  132. writeFileSync(join(work, 'README.md'), '# Alpha project\n\nSome **strong** text with `code` and a [link](https://example.org/x).\n\n- one\n- two\n\n```\nlet x = 1 < 2\n```\n');
  133. writeFileSync(join(work, 'src/a.txt'), 'line one\nline two\n');
  134. git('add', '-A'); git('commit', '-q', '-m', 'first');
  135. writeFileSync(join(work, 'src/a.txt'), 'line one\nline two changed\nline three\n'); git('add', '-A'); git('commit', '-q', '-m', 'second');
  136. git('push', '-q', '-f', join(STORE, 'git', 'alpha.git'), 'main');
  137. const sha = git('rev-parse', 'HEAD').trim(); process.env.E2E_SHA = sha;
  138. console.log('tag', TAG, 'app', APP, 'sha', sha);
  139. await walk(390, true); await walk(1280, true);
  140. // signed out: drop the gitoria session cookie
  141. const cks = (await page.send('Network.getAllCookies')).cookies.filter(c => /gitoria/.test(c.domain) || /^gitoriasid/.test(c.name));
  142. for (const c of cks) await page.send('Network.deleteCookies', { name: c.name, domain: c.domain, path: c.path });
  143. await walk(390, false);
  144. const bad = results.filter(r => (r.w < 600 && r.tapsSmall > 0) || r.scrollWidth > r.w || r.inputsSmall > 0 || r.boxesOver > 0);
  145. const desk = results.filter(r => r.w >= 600 && r.tapsSmall > 0).length; console.log('1280 audits with a target under 44 px (the theme is denser there on purpose):', desk);
  146. console.log(`SUMMARY ${TAG}: ${results.length} measurements, ${bad.length} with taps<44 / wider than screen / inputs<16 / boxes over`);
  147. for (const r of bad) console.log(' BAD', J(r));
  148. const mfail = marks.filter(m => !m.ok); console.log(`MENU MARKER ${TAG}: ${marks.length} checks, ${mfail.length} failed`); if (mfail.length) process.exitCode = 1;
  149. report('end'); console.log('console errors counted (tunnel network noise left out):', seen.size);
  150. writeFileSync(join(SHOTS, `${TAG}-results.json`), J(results, null, 1));
  151. await page.send('Emulation.clearDeviceMetricsOverride'); await page.send('Emulation.setTouchEmulationEnabled', { enabled: false });
  152. await page.goto('about:blank');
  153. } catch (e) { console.log('E2E ERROR', e.stack || e); console.log('SERVER LOG', slog().slice(-2500)); process.exitCode = 1; }
  154. finally {
  155. try { if (process.env.E2E_RESTORE && browserConn) await browserConn.send('Target.activateTarget', { targetId: process.env.E2E_RESTORE }); } catch {}
  156. try { server && server.kill('SIGTERM'); } catch {} try { ident && ident.stop && ident.stop(); } catch {}
  157. await sleep(500); process.exit(process.exitCode || 0);
  158. }

Branches

Latest commits

  • fe209ffeMerge branch 'w56-owner-members' into mainGitoria
  • fa0754c8|||PR repository owner transfer and members API (#55)mre
  • 8862e537Merge branch 'w55-rename-org' into mainGitoria
  • 014d2b7fOne immutable readers snapshot per move for the left-organization event (#53)mre
  • 1859d506Decide who hears a repo left its organization by its readers before the move (#53)mre
  • 499f25f2Review fixes for the Settings organization move (#53)mre
  • ed3b922b|||PR move a repository into an organization in Settings (#53)mre
  • 74ec2af8Merge branch 'w54-repo-rename-pr' into mainGitoria
  • 9f7ce8d8Preserve rename compatibility and live page titlesmre
  • c3d95b6e|||PR separate names and addresses, rename repositories in Settings (#53)mre
  • ce08920dMerge branch 'w52c-header-phone' into mainGitoria
  • 0bab9e46|||PR header: ident status wraps on phones instead of clippingmre
  • e7af3eceMerge branch 'w52b-approval-followup' into mainGitoria
  • c01e66c6|||PR approvals follow-up: live Merge after status writes, helpers (#52)mre
  • 841da497Merge branch 'w53-pulls-speed-pr' into mainGitoria
  • 80307ae2|||PR pulls page cache: live PR numbers, complete scans onlymre
  • 69141f65|||PR pulls page: cache the git part per repo by branch tipsmre
  • 155861f6Merge branch 'w52-person-approval' into mainGitoria
  • b5435de8|||PR person approvals: second Kunibert round (#52)mre
  • 3a8b2fb8|||PR person approvals: Kunibert review fixes (#52)mre