gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit07ab845b07ab845bvendor: Hybriel set-day50 (run() leak fix #335)mre07ab845b/tests/pr-page.mjs

25.4 KB

  1. // tests/pr-page.mjs — GATE OF THE PULL REQUEST PAGE (gitoria#45, part of the push API #38; contract docs/apps-api.md §4 events, §5 shapes).
  2. // Real HTTP against a real local gitoria + its own ident (tests/identkit.mjs) + a tiny receiver for two apps, the real `git` binary for the push, a headless Chrome
  3. // (390 and 1280 px) for what people click. /pulls/N by number (200, 404 for an unknown one), Markdown shown as text (a <script> body), the apps' reviews, threads and
  4. // verdicts, a member's comment / reply / resolve / reopen / "Review again" and WHICH app hears of it (only that one), a non-member: no form and refused faces,
  5. // Settings: no empty "Apps" heading for a non-owner.
  6. // node tests/pr-page.mjs (GITORIA_PRPAGE_PORT default 8720 = gitoria, +1 receiver, +2 ident, 8723-8729 Chrome debug ports)
  7. import { spawn, spawnSync } from 'node:child_process';
  8. import { request, createServer } from 'node:http';
  9. import { mkdirSync, rmSync, writeFileSync, existsSync } from 'node:fs';
  10. import { dirname, join, resolve } from 'node:path';
  11. import { fileURLToPath } from 'node:url';
  12. import { startIdent } from './identkit.mjs';
  13. import { launchBrowser } from './cdp.mjs';
  14. if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';
  15. const HERE = dirname(fileURLToPath(import.meta.url));
  16. const APP = resolve(HERE, '..');
  17. const PORT = Number(process.env.GITORIA_PRPAGE_PORT || 8720), RPORT = PORT + 1, IDENT_PORT = PORT + 2;
  18. process.env.HL_CHROME_ARGS = '--host-resolver-rules=MAP *.gitoria.test 127.0.0.1, MAP gitoria.test 127.0.0.1';
  19. const IDENT_DIR = process.env.GITORIA_GATE_IDENT_DIR || [resolve(APP, '../ident.worldapi.org'), '/media/STORAGE/projects/WorldAPI/ident.worldapi.org'].find(d => existsSync(join(d, 'project.hl')));
  20. const SCRATCH = join(APP, '.scratch');
  21. const STORE = join(SCRATCH, 'prpage-store');
  22. const DB = join(STORE, 'mpackdb'), GIT = join(STORE, 'git'), WORK = join(STORE, 'work');
  23. const BIN = join(APP, 'bin/hybriel');
  24. const J = JSON.stringify, sleep = (ms) => new Promise(r => setTimeout(r, ms));
  25. let passes = 0, failures = 0;
  26. const check = (label, ok, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + String(detail).slice(0, 600)}`); if (ok) passes++; else failures++; };
  27. const waitFor = async (fn, ms = 20000) => { const t0 = Date.now(); for (;;) { const v = await fn(); if (v) return v; if (Date.now() - t0 > ms) return null; await sleep(100); } };
  28. // ---- the receiver of the two apps: /a (Alpha) and /b (Beta)
  29. const got = [];
  30. const receiver = createServer((req, res) => { const c = []; req.on('data', d => c.push(d)); req.on('end', () => { got.push({ path: req.url, headers: req.headers, body: Buffer.concat(c).toString('utf8') }); res.statusCode = 204; res.end(); }); });
  31. await new Promise(r => receiver.listen(RPORT, '127.0.0.1', r));
  32. const evAt = (p, since = 0) => got.slice(since).filter(g => g.path === p && g.headers['x-push-event'] !== 'ping').map(g => ({ event: g.headers['x-push-event'], ...JSON.parse(g.body) }));
  33. function raw(method, path, { host = `gitoria.test:${PORT}`, headers = {}, body = null, cookie = null } = {}) {
  34. return new Promise((res, rej) => {
  35. const h = { host, ...headers }; if (cookie) h.cookie = cookie;
  36. if (body !== null) h['content-length'] = Buffer.byteLength(body);
  37. const r = request({ host: '127.0.0.1', port: PORT, method, path, headers: h }, (m) => { const c = []; m.on('data', d => c.push(d)); m.on('end', () => res({ status: m.statusCode, headers: m.headers, body: Buffer.concat(c).toString('utf8') })); });
  38. r.on('error', rej); if (body !== null) r.write(body); r.end();
  39. });
  40. }
  41. const gitEnv = { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_CONFIG_GLOBAL: '/dev/null', GIT_AUTHOR_NAME: 'Dev', GIT_AUTHOR_EMAIL: '[email protected]', GIT_COMMITTER_NAME: 'Dev', GIT_COMMITTER_EMAIL: '[email protected]' };
  42. const git = (cwd, args) => { const r = spawnSync('git', args, { cwd, encoding: 'utf8', env: gitEnv }); return { ok: r.status === 0, out: (r.stdout || '').trim(), err: (r.stderr || '').trim() }; };
  43. const must = (cwd, args) => { const r = git(cwd, args); if (!r.ok) throw new Error('git ' + args.join(' ') + ': ' + r.err); return r.out; };
  44. const procs = [], browsers = [];
  45. let log = '';
  46. function spawnServer(extra) {
  47. const p = spawn(BIN, ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, GITORIA_PORT: String(PORT), GITORIA_WATCH: '0', GITORIA_PUBLIC_URL: `http://gitoria.test:${PORT}`, GITORIA_SSH_SECRET: 'sshsecret-prpage-gate', GITORIA_TICKETS_URL: 'http://127.0.0.1:1',
  48. GITORIA_APP_HOSTS: `http://127.0.0.1:${RPORT}`, GITORIA_EVENTS_TICK: '0.3', ...extra } });
  49. p.stdout.on('data', d => log += d); p.stderr.on('data', d => log += d); procs.push(p);
  50. }
  51. const cleanup = async () => { for (const b of browsers) try { await b.close(); } catch {} for (const p of procs) try { p.kill('SIGTERM'); } catch {} try { receiver.close(); } catch {} };
  52. process.on('exit', () => { for (const p of procs) try { p.kill('SIGTERM'); } catch {} });
  53. let ident = null, pg = null, api = null, tA = null;
  54. try {
  55. rmSync(STORE, { recursive: true, force: true }); for (const d of [DB, GIT, WORK]) mkdirSync(d, { recursive: true });
  56. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });
  57. const alice = await ident.signIn('[email protected]'), bob = await ident.signIn('[email protected]'), carol = await ident.signIn('[email protected]');
  58. const BASE = `http://gitoria.test:${PORT}`;
  59. const app = await ident.registerApp(alice, 'gitoria (pr page gate)', [BASE]);
  60. spawnServer({ GITORIA_STORAGE: DB, GITORIA_SESSIONS: join(STORE, 'sessions') + '/', GITORIA_GIT: GIT, IDENT_URL: ident.base, IDENT_EXCHANGE_URL: ident.base, IDENT_API_KEY: app.key, IDENT_API_SECRET: app.secret });
  61. for (let i = 0; i < 960; i++) { try { if ((await raw('GET', '/api/repos')).status === 200) break; } catch {} await sleep(250); if (i === 959) throw new Error('gitoria did not come up\n' + log); }
  62. const get = (path, o = {}) => raw('GET', path, o);
  63. const cookieOf = (r) => (r.headers['set-cookie'] || []).map(c => c.split(';')[0])[0] || null;
  64. const login = async (who) => { const ck = cookieOf(await get('/')); const code = await ident.selectorCode(who, app, BASE); const cb = await get('/login/callback?ident_code=' + code + '&next=%2F', { cookie: ck }); return { cookie: cookieOf(cb) || ck }; };
  65. let n = 0;
  66. const face = async (who, event, payload) => { const r = await raw('POST', '/__hl/emit', { headers: { 'content-type': 'application/json' }, cookie: who && who.cookie, body: J({ t: 'emit', i: ++n, event, payload }) }); let j = null; try { j = JSON.parse(r.body); } catch {} return { status: r.status, value: j && j.value }; };
  67. const A = await login(alice), B = await login(bob), C = await login(carol);
  68. await face(A, 'gitoriaSaveName', ['Alice']); await face(B, 'gitoriaSaveName', ['Bob']); await face(C, 'gitoriaSaveName', ['Carol']);
  69. const token = (await face(A, 'gitoriaMakeToken', ['gate'])).value.token;
  70. const H = 'prp.gitoria.test:' + PORT;
  71. const page = (p, who) => get(p, { host: H, cookie: who && who.cookie });
  72. check('alice creates prp; bob becomes a member; carol is nobody', !!(await face(A, 'gitoriaCreate', ['prp', 'x'])).value.repo && !(await face(A, 'gitoriaChangeMember', ['prp', 'Bob', true])).value.error);
  73. const addA = (await face(A, 'gitoriaAppAdd', ['prp', 'Alpha', `http://127.0.0.1:${RPORT}/a`])).value;
  74. const addB = (await face(A, 'gitoriaAppAdd', ['prp', 'Beta', `http://127.0.0.1:${RPORT}/b`])).value;
  75. check('two apps are connected', !!addA.key && !!addB.key, J(addA));
  76. const idA = ((addB.rows || []).find(x => x.name === 'Alpha') || {}).id, idB = ((addB.rows || []).find(x => x.name === 'Beta') || {}).id;
  77. check('their ids are known', !!idA && !!idB, J(addB.rows));
  78. // ---- the PR: main + a branch with a |||PR commit
  79. const W = join(WORK, 'w'); mkdirSync(W);
  80. const URL = `http://app:${token}@prp.gitoria.test:${PORT}/prp.git`, RES = ['-c', `http.curloptResolve=prp.gitoria.test:${PORT}:127.0.0.1`];
  81. must(W, ['init', '-q', '-b', 'main']); writeFileSync(join(W, 'a.txt'), 'a\n'); must(W, ['add', '.']); must(W, ['commit', '-q', '-m', 'base']);
  82. check('push main', git(W, [...RES, 'push', URL, 'main']).ok);
  83. must(W, ['checkout', '-q', '-b', 'feat']); writeFileSync(join(W, 'f.txt'), 'one\ntwo\nthree\n'); must(W, ['add', '.']);
  84. must(W, ['commit', '-q', '-m', '|||PR Add the f file proj#12', '-m', 'Body']);
  85. const head = must(W, ['rev-parse', 'HEAD']);
  86. check('push the |||PR branch', git(W, [...RES, 'push', URL, 'feat']).ok);
  87. const tokenOf = async (key) => JSON.parse((await raw('POST', '/api/apps/token', { host: H, headers: { authorization: 'Bearer ' + key } })).body).token;
  88. tA = await tokenOf(addA.key); const tB = await tokenOf(addB.key);
  89. api = async (t, method, path, obj) => { const r = await raw(method, '/api' + path, { host: H, headers: { authorization: 'Bearer ' + t, 'content-type': 'application/json' }, body: obj === undefined ? null : J(obj) }); let j = null; try { j = JSON.parse(r.body); } catch {} return { status: r.status, json: j }; };
  90. const EVIL = 'Fix <script>alert(1)</script> and <img src=x onerror=alert(2)>';
  91. const rvA = await api(tA, 'POST', '/pulls/1/reviews', { head, verdict: 'request_changes', body: EVIL + ' **bold**', comments: [{ path: 'f.txt', line: 2, body: 'inline <script>alert(3)</script> here' }] });
  92. const rvB = await api(tB, 'POST', '/pulls/1/reviews', { head, verdict: 'approve', body: 'Looks fine' });
  93. check('the two apps review through the API', rvA.status === 201 && rvB.status === 201 && rvA.json.threads.length === 1, J(rvA.json));
  94. const threadId = rvA.json.threads[0].id;
  95. // ---- 1. the page, signed out
  96. const p1 = await page('/pulls/1');
  97. const t = p1.body.replace(/<script type="application\/json" id="hl-seed">[\s\S]*?<\/script>/g, '').replace(/<style[\s\S]*?<\/style>/g, '').replace(/<!--[^>]*-->/g, '');
  98. check('/pulls/1 is 200 and shows the number, title, state, source → target, author, the head', p1.status === 200 && /id="pullpage"/.test(t) && />#1</.test(t) && /Add the f file/.test(t) && /id="pullstate"[^>]*>open</.test(t) && /<strong>feat<\/strong> → <strong>main<\/strong>/.test(t.replace(/<!--.*?-->/g, '')) && /id="pullauthor"[^>]*>Alice</.test(t) && t.includes(head.slice(0, 8)), t.slice(t.indexOf('pullpage'), t.indexOf('pullpage') + 600));
  99. check('the ticket reference in the title is a plain text here (no tickets project connected)', /proj#12/.test(t));
  100. check('each app\'s current verdict: Alpha requested changes, Beta approved', /class="request_changes"[^>]*>\s*<strong>Alpha<\/strong>[^<]*<span>requested changes/.test(t.replace(/<!--.*?-->/g, '')) && /class="approve"[^>]*>\s*<strong>Beta<\/strong>[^<]*<span>approved/.test(t.replace(/<!--.*?-->/g, '')), t.slice(t.indexOf('pullverdicts'), t.indexOf('pullverdicts') + 500));
  101. check('the review body and the thread (path:line, comment) are there', /Fix /.test(t) && /f\.txt:2/.test(t) && /inline /.test(t) && /Looks fine/.test(t));
  102. check('Markdown is shown as TEXT: the <script> and <img onerror> are escaped, never HTML', !/<script>alert|<img /.test(t) && /&lt;script&gt;alert\(1\)&lt;\/script&gt;/.test(t) && /&lt;img src=x onerror=alert\(2\)&gt;/.test(t) && /&lt;script&gt;alert\(3\)&lt;\/script&gt;/.test(t), t.slice(t.indexOf('Fix'), t.indexOf('Fix') + 500));
  103. check('signed out: no comment form, no reply form, no Review again, a read-only hint', !/id="commentform"|rows="3"|Review again|commentbody/.test(t) && /id="readonlyhint"/.test(t));
  104. const pl = await page('/pulls');
  105. check('the /pulls list links the title to the PR page', /href="\/pulls\/1"[^>]*>Add the f file/.test(pl.body.replace(/<!--.*?-->/g, '')), pl.body.slice(pl.body.indexOf('pulllist'), pl.body.indexOf('pulllist') + 400));
  106. for (const bad of ['/pulls/99', '/pulls/0', '/pulls/abc', '/pulls/1x', '/pulls/-1', '/pulls/1.5']) { const r = await page(bad); check(`${bad} is 404`, r.status === 404, r.status); }
  107. const noRepo = await get('/pulls/1', { host: 'nope.gitoria.test:' + PORT });
  108. check('/pulls/1 of a repo that does not exist is 404', noRepo.status === 404, noRepo.status);
  109. const noStyle = (b) => b.replace(/<style[\s\S]*?<\/style>/g, '').replace(/<script type="application\/json" id="hl-seed">[\s\S]*?<\/script>/g, '');
  110. const asC = await page('/pulls/1', C);
  111. check('a signed-in non-member sees the same read-only page', asC.status === 200 && !/id="commentform"|rows="3"|Review again/.test(noStyle(asC.body)) && /id="readonlyhint"/.test(asC.body), asC.status + ' ' + noStyle(asC.body).slice(0, 300));
  112. const asB = await page('/pulls/1', B), asA = await page('/pulls/1', A);
  113. check('the owner and the member get the comment form, a reply form and a Review again button per app', [asA, asB].every(r => /id="commentform"/.test(r.body) && /rows="3"/.test(r.body) && /Review again: <!--[^>]*-->Alpha|Review again: Alpha/.test(r.body.replace(/<!--[^>]*-->/g, '')) && /Review again: Beta/.test(r.body.replace(/<!--[^>]*-->/g, ''))));
  114. // ---- 2. forged faces: nobody, a non-member
  115. await waitFor(() => got.filter(g => g.headers['x-push-event'] === 'ping').length >= 2); await sleep(1000);
  116. const before = got.length;
  117. const forged = [];
  118. for (const who of [null, C]) {
  119. forged.push((await face(who, 'gitoriaPrComment', ['prp', '1', 'forged'])).value);
  120. forged.push((await face(who, 'gitoriaPrReply', ['prp', '1', threadId, 'forged'])).value);
  121. forged.push((await face(who, 'gitoriaPrResolve', ['prp', '1', threadId, true])).value);
  122. forged.push((await face(who, 'gitoriaPrAskAgain', ['prp', '1', idA])).value);
  123. }
  124. check('forged faces (signed out and non-member) are refused, nothing is stored', forged.every(v => v && v.error && !v.view), J(forged));
  125. await sleep(1200);
  126. check('...and no app heard of any of them', got.length === before, got.length - before);
  127. check('...the conversation is still empty (API)', (await api(tA, 'GET', '/pulls/1/comments')).json.comments.length === 0 && !(await api(tA, 'GET', '/pulls/1/threads')).json.threads[0].resolved);
  128. // ---- 3. a member writes: Bob
  129. let k = got.length;
  130. let r = (await face(B, 'gitoriaPrComment', ['prp', '1', 'Hello <b>team</b> @alpha reset'])).value;
  131. check('Bob\'s comment is stored and comes back in the page data', r && r.view && r.view.conversation.length === 1 && r.view.conversation[0].author === 'Bob', J(r));
  132. await waitFor(() => evAt('/a', k).length >= 1 && evAt('/b', k).length >= 1); await sleep(800);
  133. let ea = evAt('/a', k), eb = evAt('/b', k);
  134. check('pull_comment/created goes to EVERY connected app, sender Bob, with pull and comment', ea.length === 1 && eb.length === 1 && [ea[0], eb[0]].every(e => e.event === 'pull_comment' && e.action === 'created' && e.sender.name === 'Bob' && e.pull.number === 1 && e.comment.body === 'Hello <b>team</b> @alpha reset' && e.comment.author.type === 'user' && e.comment.author.name === 'Bob' && Number.isInteger(e.comment.seq)), J([ea, eb]).slice(0, 400));
  135. const conv = (await api(tA, 'GET', '/pulls/1/comments')).json.comments;
  136. check('API: the conversation has Bob\'s comment (author type user)', conv.length === 1 && conv[0].author.type === 'user' && conv[0].author.name === 'Bob' && conv[0].body.startsWith('Hello'));
  137. k = got.length;
  138. r = (await face(B, 'gitoriaPrReply', ['prp', '1', threadId, 'Will do <i>soon</i>'])).value;
  139. check('Bob\'s reply lands in the thread', r && r.view && r.view.threads[0].comments.length === 2 && r.view.threads[0].comments[1].author === 'Bob', J(r).slice(0, 300));
  140. await waitFor(() => evAt('/a', k).length >= 1); await sleep(1000);
  141. ea = evAt('/a', k); eb = evAt('/b', k);
  142. check('review_comment/created goes to THAT app (Alpha) only, with pull, thread and comment', ea.length === 1 && eb.length === 0 && ea[0].event === 'review_comment' && ea[0].action === 'created' && ea[0].thread.id === threadId && ea[0].thread.path === 'f.txt' && ea[0].thread.line === 2 && ea[0].comment.body === 'Will do <i>soon</i>' && ea[0].comment.seq > conv[0].seq && ea[0].sender.name === 'Bob' && ea[0].pull.number === 1, J([ea, eb]).slice(0, 500));
  143. const th = (await api(tA, 'GET', '/pulls/1/threads')).json.threads[0];
  144. check('API: the thread has the app\'s comment then Bob\'s, seq growing', th.comments.length === 2 && th.comments[1].author.type === 'user' && th.comments[1].seq > th.comments[0].seq);
  145. k = got.length;
  146. r = (await face(B, 'gitoriaPrResolve', ['prp', '1', threadId, true])).value;
  147. check('resolve: the page data marks the thread resolved', r && r.view && r.view.threads[0].resolved === true && /resolved/.test(r.view.threads[0].mark) && r.view.threads[0].toggleLabel === 'Reopen', J(r).slice(0, 300));
  148. await waitFor(() => evAt('/a', k).length >= 1); await sleep(800);
  149. ea = evAt('/a', k); eb = evAt('/b', k);
  150. check('review_thread/resolved to Alpha only', ea.length === 1 && eb.length === 0 && ea[0].event === 'review_thread' && ea[0].action === 'resolved' && ea[0].thread.resolved === true && ea[0].thread.id === threadId && ea[0].sender.name === 'Bob', J([ea, eb]).slice(0, 400));
  151. k = got.length;
  152. await face(B, 'gitoriaPrResolve', ['prp', '1', threadId, true]); await sleep(1000);
  153. check('resolving a resolved thread again raises nothing', got.length === k);
  154. r = (await face(B, 'gitoriaPrResolve', ['prp', '1', threadId, false])).value;
  155. await waitFor(() => evAt('/a', k).length >= 1); await sleep(800);
  156. ea = evAt('/a', k); eb = evAt('/b', k);
  157. check('reopen: review_thread/unresolved to Alpha only', r && r.view.threads[0].resolved === false && ea.length === 1 && eb.length === 0 && ea[0].action === 'unresolved' && ea[0].thread.resolved === false, J([ea, eb]).slice(0, 300));
  158. check('API: Alpha sees the thread open again', (await api(tA, 'GET', '/pulls/1/threads')).json.threads[0].resolved === false);
  159. k = got.length;
  160. r = (await face(B, 'gitoriaPrAskAgain', ['prp', '1', idB])).value;
  161. check('"Review again" for Beta answers with a notice', r && r.view && /Beta/.test(r.notice || ''), J(r).slice(0, 200));
  162. await waitFor(() => evAt('/b', k).length >= 1); await sleep(1000);
  163. ea = evAt('/a', k); eb = evAt('/b', k);
  164. check('review_requested/requested goes to Beta only, with the pull', eb.length === 1 && ea.length === 0 && eb[0].event === 'review_requested' && eb[0].action === 'requested' && eb[0].pull.number === 1 && eb[0].sender.name === 'Bob', J([ea, eb]).slice(0, 400));
  165. check('Review again with an app of another repo / an unknown id is refused', !!(await face(B, 'gitoriaPrAskAgain', ['prp', '1', 'nosuchapp'])).value.error);
  166. // ---- 4. limits and unknown ids
  167. const long = (await face(B, 'gitoriaPrComment', ['prp', '1', 'x'.repeat(65537)])).value, empty = (await face(B, 'gitoriaPrComment', ['prp', '1', ' '])).value;
  168. const bad = (await face(B, 'gitoriaPrReply', ['prp', '1', 'nosuchthread', 'x'])).value, badN = (await face(B, 'gitoriaPrComment', ['prp', '99', 'x'])).value;
  169. check('over 65,536 characters, empty, an unknown thread and an unknown PR number are refused', [long, empty, bad, badN].every(v => v && v.error && !v.view), J([long, empty, bad, badN]).slice(0, 300));
  170. const fresh = await page('/pulls/1', B);
  171. check('a second visit (reload) shows the stored state: conversation, reply, no resolved mark', /Hello/.test(fresh.body) && /Will do/.test(fresh.body) && /Bob/.test(fresh.body));
  172. // ---- 5. Settings: the Apps heading is the owner's
  173. const sA = (await page('/settings', A)).body, sB = (await page('/settings', B)).body, sC = (await page('/settings', C)).body, sN = (await page('/settings')).body;
  174. const hasApps = (b) => />Apps<\/h2>/.test(b.replace(/<!--[^>]*-->/g, ''));
  175. check('Settings: the owner has the Apps heading; a member, another user and a signed-out visitor do not', hasApps(sA) && !hasApps(sB) && !hasApps(sC) && !hasApps(sN), [hasApps(sA), hasApps(sB), hasApps(sC), hasApps(sN)].join());
  176. // ---- 6. in a browser, at 390 and 1280: Bob clicks
  177. const br = await launchBrowser({ debugPortRange: [PORT + 3, PORT + 9] }); browsers.push(br);
  178. pg = await br.newPage();
  179. const sid = B.cookie.split('=')[1];
  180. await pg.send('Network.enable'); await pg.send('Network.setCookie', { name: 'gitoriasid', value: sid, domain: '.gitoria.test', path: '/' });
  181. const q = (sel) => pg.evaluate(`(document.querySelector(${J(sel)}) || {}).textContent || ''`);
  182. const noOverflow = () => pg.evaluate('document.documentElement.scrollWidth <= window.innerWidth');
  183. const shot = async (name) => { const { data } = await pg.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true }); mkdirSync(SCRATCH, { recursive: true }); writeFileSync(join(SCRATCH, `gate-prpage-${name}.png`), Buffer.from(data, 'base64')); };
  184. for (const [w, h, label] of [[390, 844, '390'], [1280, 900, '1280']]) {
  185. await pg.send('Emulation.setDeviceMetricsOverride', { width: w, height: h, deviceScaleFactor: 1, mobile: w < 600 });
  186. await pg.goto(`http://prp.gitoria.test:${PORT}/pulls/1`); await pg.waitFor(`!!document.querySelector('#pullpage') && !!document.querySelector('#commentform') && !!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1`, { timeout: 30000 });
  187. check(`${label}px: the page shows title, verdicts, thread, forms and does not overflow sideways`, /Add the f file/.test(await q('#pulltitle')) && /Alpha/.test(await q('#pullverdicts')) && /f\.txt:2/.test(await q('#threadlist')) && await noOverflow());
  188. const boxes = await pg.evaluate(`[...document.querySelectorAll('#pullpage button, #pullpage textarea')].map(e => { const b = e.getBoundingClientRect(); return [b.width, b.height, b.left, b.right] })`);
  189. check(`${label}px: buttons and fields are inside the viewport (and 44 px tall on the phone)`, boxes.length >= 5 && boxes.every(([bw, bh, l, rr]) => (w > 600 || bh >= 43) && l >= 0 && rr <= w + 1), J(boxes));
  190. const text = `from the browser ${label}`;
  191. await pg.type('#commentbody', text); await pg.click('#commentsave');
  192. await pg.waitFor(`document.querySelector('#conversation').textContent.includes(${J(text)})`, { timeout: 20000 });
  193. check(`${label}px: a comment typed and sent shows at once (oldest first, ours last) and the field is empty`, (await pg.evaluate(`[...document.querySelectorAll('#conversation > li')].pop().textContent.includes(${J(text)})`)) && (await pg.evaluate(`document.querySelector('#commentbody').value`)) === '');
  194. const reply = `reply ${label}`;
  195. await pg.evaluate(`document.querySelector('#threadlist form textarea').focus()`); await pg.type('#threadlist form textarea', reply); await pg.click('#threadlist form button[type=submit]');
  196. await pg.waitFor(`document.querySelector('#threadlist').textContent.includes(${J(reply)})`, { timeout: 20000 });
  197. check(`${label}px: a reply shows in its thread`, true);
  198. await pg.click('#threadlist form button.quiet'); await pg.waitFor(`/resolved/.test(document.querySelector('#threadlist .mark').textContent)`, { timeout: 20000 });
  199. check(`${label}px: Resolve marks the thread resolved and the button says Reopen`, /Reopen/.test(await q('#threadlist form button.quiet')));
  200. await pg.click('#threadlist form button.quiet'); await pg.waitFor(`!/resolved/.test(document.querySelector('#threadlist .mark').textContent)`, { timeout: 20000 });
  201. check(`${label}px: Reopen takes the mark away`, /Resolve/.test(await q('#threadlist form button.quiet')));
  202. const k2 = got.length;
  203. await pg.click('#reviewagain button:nth-child(2)'); await pg.waitFor(`/Asked/.test(document.querySelector('#pullnotice').textContent)`, { timeout: 20000 });
  204. await waitFor(() => evAt('/b', k2).length >= 1 || evAt('/a', k2).some(e => e.event === 'review_requested'));
  205. check(`${label}px: "Review again" asks that one app (the second button: Beta) and says so`, /Beta/.test(await q('#pullnotice')) && evAt('/b', k2).some(e => e.event === 'review_requested') && !evAt('/a', k2).some(e => e.event === 'review_requested'));
  206. check(`${label}px: no sideways overflow after the clicks`, await noOverflow());
  207. await shot(label + '-member');
  208. }
  209. // the longest allowed body (65,536 characters) is stored and shown
  210. const okMax = (await face(B, 'gitoriaPrComment', ['prp', '1', 'y'.repeat(65536)])).value;
  211. check('exactly 65,536 characters is fine', okMax && okMax.view && okMax.view.conversation.length >= 2, J(okMax).slice(0, 100));
  212. // a signed-out visitor in the same browser
  213. await pg.send('Network.deleteCookies', { name: 'gitoriasid', domain: '.gitoria.test', path: '/' });
  214. await pg.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
  215. await pg.goto(`http://prp.gitoria.test:${PORT}/pulls/1`); await pg.waitFor(`!!document.querySelector('#pullpage')`, { timeout: 30000 });
  216. check('390px signed out: read-only (no form, no button) and no sideways overflow', (await pg.evaluate(`!document.querySelector('#commentform') && !document.querySelector('#threadlist form') && !document.querySelector('#reviewagain')`)) && await noOverflow());
  217. await shot('390-readonly');
  218. await pg.goto(`http://prp.gitoria.test:${PORT}/pulls/99`);
  219. check('an unknown number shows the 404 page in the browser', /Page not found/.test(await q('#notfoundtitle')));
  220. await pg.close();
  221. } catch (e) {
  222. console.log('FAIL gate crashed — ' + (e && e.stack || e)); failures++; if (log) console.log(log.slice(-1500)); if (pg) { try { console.log('DOM ' + await pg.evaluate(`document.querySelector('#pullerror').textContent + ' | ' + document.querySelector('#commentbody').value + ' | ' + [...document.querySelectorAll('#conversation > li')].map(l => l.textContent.slice(0, 50)).join(' // ')`)); console.log('API ' + J((await api(tA, 'GET', '/pulls/1/comments')).json.comments.map(c => c.body.slice(0, 30)))); } catch {} } if (pg) console.log('CONSOLE ' + J(pg.messages.slice(-8)).slice(0, 2000));
  223. } finally {
  224. await cleanup(); try { if (ident) await ident.stop(); } catch {}
  225. }
  226. console.log(`\n${passes} passed, ${failures} failed`);
  227. process.exit(failures ? 1 : 0);

Branches

Latest commits

  • 07ab845bvendor: Hybriel set-day50 (run() leak fix #335)mre
  • 71b2fa4blog: hybriel#335mre
  • bd94cc7elog: #25 cause found (run() leak)mre
  • 565cb508log: H25 round 1mre
  • 90a0af84log: H25 startedmre
  • 87bd53b8mission H25mre
  • 71a746cflog: day48 livemre
  • bf568e14log: V48 mergedmre
  • 09955dedMerge v48: Hybriel set-day48, theme layouts ce4a0bamre
  • f2a2b0cevendor: Hybriel set-day48, theme layouts ce4a0bamre
  • 5d0834e7log: Apollo model rulemre
  • fe8e5bd5log: #25 sample, V48 missionmre
  • 8580c5d9log: theme fix from Atlasmre
  • 46823d93log: Apollo budget correctionmre
  • f6d32341log: Apollo on budget and #25 nextmre
  • d7184f53log: batch live, #25 evidencemre
  • 5e25e816log: W61 mergedmre
  • aafe330dTidy: drop evidence JSON (kept in scratch), collapse blank linesmre
  • aca1fda1Merge W61: theme from layouts 17e0f03, Views refer to Style rules (gitoria#37 #27)mre
  • 03cb650blog: W61 theme decisionmre