gitoria

gitoria

All repositories: gitoria

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

25.6 KB

  1. import { requiredPort, requiredPortRange } from './gate-ports.mjs';
  2. // 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).
  3. // 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
  4. // (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
  5. // 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,
  6. // Settings: no empty "Apps" heading for a non-owner.
  7. // node tests/pr-page.mjs (GITORIA_PRPAGE_PORT required = gitoria, +1 receiver, +2 ident, 8723-8729 Chrome debug ports)
  8. import { spawn, spawnSync } from 'node:child_process';
  9. import { request, createServer } from 'node:http';
  10. import { mkdirSync, rmSync, writeFileSync, existsSync } from 'node:fs';
  11. import { dirname, join, resolve } from 'node:path';
  12. import { fileURLToPath } from 'node:url';
  13. import { startIdent } from './identkit.mjs';
  14. import { launchBrowser } from './cdp.mjs';
  15. if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';
  16. const HERE = dirname(fileURLToPath(import.meta.url));
  17. const APP = resolve(HERE, '..');
  18. const PORT = requiredPort('GITORIA_PRPAGE_PORT'), RPORT = PORT + 1, IDENT_PORT = PORT + 2;
  19. process.env.HL_CHROME_ARGS = '--host-resolver-rules=MAP *.gitoria.test 127.0.0.1, MAP gitoria.test 127.0.0.1';
  20. 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')));
  21. const SCRATCH = join(APP, '.scratch');
  22. const STORE = join(SCRATCH, 'prpage-store');
  23. const DB = join(STORE, 'mpackdb'), GIT = join(STORE, 'git'), WORK = join(STORE, 'work');
  24. const BIN = join(APP, 'bin/hybriel');
  25. const J = JSON.stringify, sleep = (ms) => new Promise(r => setTimeout(r, ms));
  26. let passes = 0, failures = 0;
  27. const check = (label, ok, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + String(detail).slice(0, 600)}`); if (ok) passes++; else failures++; };
  28. 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); } };
  29. // ---- the receiver of the two apps: /a (Alpha) and /b (Beta)
  30. const got = [];
  31. 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(); }); });
  32. await new Promise(r => receiver.listen(RPORT, '127.0.0.1', r));
  33. 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) }));
  34. function raw(method, path, { host = `gitoria.test:${PORT}`, headers = {}, body = null, cookie = null } = {}) {
  35. return new Promise((res, rej) => {
  36. const h = { host, ...headers }; if (cookie) h.cookie = cookie;
  37. if (body !== null) h['content-length'] = Buffer.byteLength(body);
  38. 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') })); });
  39. r.on('error', rej); if (body !== null) r.write(body); r.end();
  40. });
  41. }
  42. 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]' };
  43. 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() }; };
  44. const must = (cwd, args) => { const r = git(cwd, args); if (!r.ok) throw new Error('git ' + args.join(' ') + ': ' + r.err); return r.out; };
  45. const procs = [], browsers = [];
  46. let log = '';
  47. function spawnServer(extra) {
  48. 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',
  49. GITORIA_APP_HOSTS: `http://127.0.0.1:${RPORT}`, GITORIA_EVENTS_TICK: '0.3', ...extra } });
  50. p.stdout.on('data', d => log += d); p.stderr.on('data', d => log += d); procs.push(p);
  51. }
  52. 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 {} };
  53. process.on('exit', () => { for (const p of procs) try { p.kill('SIGTERM'); } catch {} });
  54. let ident = null, pg = null, api = null, tA = null;
  55. try {
  56. rmSync(STORE, { recursive: true, force: true }); for (const d of [DB, GIT, WORK]) mkdirSync(d, { recursive: true });
  57. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });
  58. const alice = await ident.signIn('[email protected]'), bob = await ident.signIn('[email protected]'), carol = await ident.signIn('[email protected]');
  59. const BASE = `http://gitoria.test:${PORT}`;
  60. const app = await ident.registerApp(alice, 'gitoria (pr page gate)', [BASE]);
  61. 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 });
  62. 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); }
  63. const get = (path, o = {}) => raw('GET', path, o);
  64. const cookieOf = (r) => (r.headers['set-cookie'] || []).map(c => c.split(';')[0])[0] || null;
  65. 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 }; };
  66. let n = 0;
  67. 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 }; };
  68. const A = await login(alice), B = await login(bob), C = await login(carol);
  69. await face(A, 'gitoriaSaveName', ['Alice']); await face(B, 'gitoriaSaveName', ['Bob']); await face(C, 'gitoriaSaveName', ['Carol']);
  70. const token = (await face(A, 'gitoriaMakeToken', ['gate'])).value.token;
  71. const H = 'prp.gitoria.test:' + PORT;
  72. const page = (p, who) => get(p, { host: H, cookie: who && who.cookie });
  73. 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);
  74. const addA = (await face(A, 'gitoriaAppAdd', ['prp', 'Alpha', `http://127.0.0.1:${RPORT}/a`])).value;
  75. const addB = (await face(A, 'gitoriaAppAdd', ['prp', 'Beta', `http://127.0.0.1:${RPORT}/b`])).value;
  76. check('two apps are connected', !!addA.key && !!addB.key, J(addA));
  77. const idA = ((addB.rows || []).find(x => x.name === 'Alpha') || {}).id, idB = ((addB.rows || []).find(x => x.name === 'Beta') || {}).id;
  78. check('their ids are known', !!idA && !!idB, J(addB.rows));
  79. // ---- the PR: main + a branch with a |||PR commit
  80. const W = join(WORK, 'w'); mkdirSync(W);
  81. const URL = `http://app:${token}@prp.gitoria.test:${PORT}/prp.git`, RES = ['-c', `http.curloptResolve=prp.gitoria.test:${PORT}:127.0.0.1`];
  82. must(W, ['init', '-q', '-b', 'main']); writeFileSync(join(W, 'a.txt'), 'a\n'); must(W, ['add', '.']); must(W, ['commit', '-q', '-m', 'base']);
  83. check('push main', git(W, [...RES, 'push', URL, 'main']).ok);
  84. must(W, ['checkout', '-q', '-b', 'feat']); writeFileSync(join(W, 'f.txt'), 'one\ntwo\nthree\n'); must(W, ['add', '.']);
  85. must(W, ['commit', '-q', '-m', '|||PR Add the f file proj#12', '-m', 'Body']);
  86. const head = must(W, ['rev-parse', 'HEAD']);
  87. check('push the |||PR branch', git(W, [...RES, 'push', URL, 'feat']).ok);
  88. const tokenOf = async (key) => JSON.parse((await raw('POST', '/api/apps/token', { host: H, headers: { authorization: 'Bearer ' + key } })).body).token;
  89. tA = await tokenOf(addA.key); const tB = await tokenOf(addB.key);
  90. 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 }; };
  91. const EVIL = 'Fix <script>alert(1)</script> and <img src=x onerror=alert(2)>';
  92. 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' }] });
  93. const rvB = await api(tB, 'POST', '/pulls/1/reviews', { head, verdict: 'approve', body: 'Looks fine' });
  94. check('the two apps review through the API', rvA.status === 201 && rvB.status === 201 && rvA.json.threads.length === 1, J(rvA.json));
  95. const threadId = rvA.json.threads[0].id;
  96. // ---- 1. the page, signed out
  97. const p1 = await page('/pulls/1');
  98. const t = p1.body.replace(/<script type="application\/json" id="hl-seed">[\s\S]*?<\/script>/g, '').replace(/<style[\s\S]*?<\/style>/g, '').replace(/<!--[^>]*-->/g, '');
  99. 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));
  100. check('the ticket reference in the title is a plain text here (no tickets project connected)', /proj#12/.test(t));
  101. 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));
  102. 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));
  103. 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));
  104. 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));
  105. const pl = await page('/pulls');
  106. 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));
  107. 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); }
  108. const noRepo = await get('/pulls/1', { host: 'nope.gitoria.test:' + PORT });
  109. check('/pulls/1 of a repo that does not exist is 404', noRepo.status === 404, noRepo.status);
  110. const noStyle = (b) => b.replace(/<style[\s\S]*?<\/style>/g, '').replace(/<script type="application\/json" id="hl-seed">[\s\S]*?<\/script>/g, '');
  111. const asC = await page('/pulls/1', C);
  112. 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));
  113. const asB = await page('/pulls/1', B), asA = await page('/pulls/1', A);
  114. 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, ''))));
  115. // ---- 2. forged faces: nobody, a non-member
  116. await waitFor(() => got.filter(g => g.headers['x-push-event'] === 'ping').length >= 2); await sleep(1000);
  117. const before = got.length;
  118. const forged = [];
  119. for (const who of [null, C]) {
  120. forged.push((await face(who, 'gitoriaPrComment', ['prp', '1', 'forged'])).value);
  121. forged.push((await face(who, 'gitoriaPrReply', ['prp', '1', threadId, 'forged'])).value);
  122. forged.push((await face(who, 'gitoriaPrResolve', ['prp', '1', threadId, true])).value);
  123. forged.push((await face(who, 'gitoriaPrAskAgain', ['prp', '1', idA])).value);
  124. }
  125. check('forged faces (signed out and non-member) are refused, nothing is stored', forged.every(v => v && v.error && !v.view), J(forged));
  126. await sleep(1200);
  127. check('...and no app heard of any of them', got.length === before, got.length - before);
  128. 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);
  129. // ---- 3. a member writes: Bob
  130. let k = got.length;
  131. let r = (await face(B, 'gitoriaPrComment', ['prp', '1', 'Hello <b>team</b> @alpha reset'])).value;
  132. 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));
  133. await waitFor(() => evAt('/a', k).length >= 1 && evAt('/b', k).length >= 1); await sleep(800);
  134. let ea = evAt('/a', k), eb = evAt('/b', k);
  135. 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));
  136. const conv = (await api(tA, 'GET', '/pulls/1/comments')).json.comments;
  137. 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'));
  138. k = got.length;
  139. r = (await face(B, 'gitoriaPrReply', ['prp', '1', threadId, 'Will do <i>soon</i>'])).value;
  140. 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));
  141. await waitFor(() => evAt('/a', k).length >= 1); await sleep(1000);
  142. ea = evAt('/a', k); eb = evAt('/b', k);
  143. 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));
  144. const th = (await api(tA, 'GET', '/pulls/1/threads')).json.threads[0];
  145. 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);
  146. k = got.length;
  147. r = (await face(B, 'gitoriaPrResolve', ['prp', '1', threadId, true])).value;
  148. 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));
  149. await waitFor(() => evAt('/a', k).length >= 1); await sleep(800);
  150. ea = evAt('/a', k); eb = evAt('/b', k);
  151. 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));
  152. k = got.length;
  153. await face(B, 'gitoriaPrResolve', ['prp', '1', threadId, true]); await sleep(1000);
  154. check('resolving a resolved thread again raises nothing', got.length === k);
  155. r = (await face(B, 'gitoriaPrResolve', ['prp', '1', threadId, false])).value;
  156. await waitFor(() => evAt('/a', k).length >= 1); await sleep(800);
  157. ea = evAt('/a', k); eb = evAt('/b', k);
  158. 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));
  159. check('API: Alpha sees the thread open again', (await api(tA, 'GET', '/pulls/1/threads')).json.threads[0].resolved === false);
  160. k = got.length;
  161. r = (await face(B, 'gitoriaPrAskAgain', ['prp', '1', idB])).value;
  162. check('"Review again" for Beta answers with a notice', r && r.view && /Beta/.test(r.notice || ''), J(r).slice(0, 200));
  163. await waitFor(() => evAt('/b', k).length >= 1); await sleep(1000);
  164. ea = evAt('/a', k); eb = evAt('/b', k);
  165. 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));
  166. check('Review again with an app of another repo / an unknown id is refused', !!(await face(B, 'gitoriaPrAskAgain', ['prp', '1', 'nosuchapp'])).value.error);
  167. // ---- 4. limits and unknown ids
  168. const long = (await face(B, 'gitoriaPrComment', ['prp', '1', 'x'.repeat(65537)])).value, empty = (await face(B, 'gitoriaPrComment', ['prp', '1', ' '])).value;
  169. const bad = (await face(B, 'gitoriaPrReply', ['prp', '1', 'nosuchthread', 'x'])).value, badN = (await face(B, 'gitoriaPrComment', ['prp', '99', 'x'])).value;
  170. 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));
  171. const fresh = await page('/pulls/1', B);
  172. 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));
  173. // ---- 5. Settings: the Apps heading is the owner's
  174. const sA = (await page('/settings', A)).body, sB = (await page('/settings', B)).body, sC = (await page('/settings', C)).body, sN = (await page('/settings')).body;
  175. const hasApps = (b) => />Apps<\/h2>/.test(b.replace(/<!--[^>]*-->/g, ''));
  176. 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());
  177. // ---- 6. in a browser, at 390 and 1280: Bob clicks
  178. const br = await launchBrowser({ debugPortRange: requiredPortRange('GITORIA_GATE_CHROME') }); browsers.push(br);
  179. pg = await br.newPage();
  180. const sid = B.cookie.split('=')[1];
  181. await pg.send('Network.enable'); await pg.send('Network.setCookie', { name: 'gitoriasid', value: sid, domain: '.gitoria.test', path: '/' });
  182. const q = (sel) => pg.evaluate(`(document.querySelector(${J(sel)}) || {}).textContent || ''`);
  183. const noOverflow = () => pg.evaluate('document.documentElement.scrollWidth <= window.innerWidth');
  184. 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')); };
  185. for (const [w, h, label] of [[390, 844, '390'], [1280, 900, '1280']]) {
  186. await pg.send('Emulation.setDeviceMetricsOverride', { width: w, height: h, deviceScaleFactor: 1, mobile: w < 600 });
  187. 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 });
  188. 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());
  189. 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] })`);
  190. 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));
  191. const text = `from the browser ${label}`;
  192. await pg.type('#commentbody', text); await pg.click('#commentsave');
  193. await pg.waitFor(`document.querySelector('#conversation').textContent.includes(${J(text)})`, { timeout: 20000 });
  194. 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`)) === '');
  195. const reply = `reply ${label}`;
  196. await pg.evaluate(`document.querySelector('#threadlist form textarea').focus()`); await pg.type('#threadlist form textarea', reply); await pg.click('#threadlist form button[type=submit]');
  197. await pg.waitFor(`document.querySelector('#threadlist').textContent.includes(${J(reply)})`, { timeout: 20000 });
  198. check(`${label}px: a reply shows in its thread`, true);
  199. await pg.click('#threadlist form button.quiet'); await pg.waitFor(`/resolved/.test(document.querySelector('#threadlist .mark').textContent)`, { timeout: 20000 });
  200. check(`${label}px: Resolve marks the thread resolved and the button says Reopen`, /Reopen/.test(await q('#threadlist form button.quiet')));
  201. await pg.click('#threadlist form button.quiet'); await pg.waitFor(`!/resolved/.test(document.querySelector('#threadlist .mark').textContent)`, { timeout: 20000 });
  202. check(`${label}px: Reopen takes the mark away`, /Resolve/.test(await q('#threadlist form button.quiet')));
  203. const k2 = got.length;
  204. // Identify the app by its id; earlier comment deliveries may still arrive here.
  205. await pg.click('#reviewagain button[value="' + idB + '"]'); await pg.waitFor(`/Asked/.test(document.querySelector('#pullnotice').textContent)`, { timeout: 20000 });
  206. await waitFor(() => ['/a', '/b'].some(path => evAt(path, k2).some(e => e.event === 'review_requested')));
  207. check(`${label}px: "Review again" asks Beta by its app id 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'));
  208. check(`${label}px: no sideways overflow after the clicks`, await noOverflow());
  209. await shot(label + '-member');
  210. }
  211. // the longest allowed body (65,536 characters) is stored and shown
  212. const okMax = (await face(B, 'gitoriaPrComment', ['prp', '1', 'y'.repeat(65536)])).value;
  213. check('exactly 65,536 characters is fine', okMax && okMax.view && okMax.view.conversation.length >= 2, J(okMax).slice(0, 100));
  214. // a signed-out visitor in the same browser
  215. await pg.send('Network.deleteCookies', { name: 'gitoriasid', domain: '.gitoria.test', path: '/' });
  216. await pg.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
  217. await pg.goto(`http://prp.gitoria.test:${PORT}/pulls/1`); await pg.waitFor(`!!document.querySelector('#pullpage')`, { timeout: 30000 });
  218. 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());
  219. await shot('390-readonly');
  220. await pg.goto(`http://prp.gitoria.test:${PORT}/pulls/99`);
  221. check('an unknown number shows the 404 page in the browser', /Page not found/.test(await q('#notfoundtitle')));
  222. await pg.close();
  223. } catch (e) {
  224. 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));
  225. } finally {
  226. await cleanup(); try { if (ident) await ident.stop(); } catch {}
  227. }
  228. console.log(`\n${passes} passed, ${failures} failed`);
  229. process.exit(failures ? 1 : 0);

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