gitoria
All repositories: gitoria
33.5 KB
import { requiredPort } from './gate-ports.mjs';// tests/reviews.mjs — GATE OF REVIEWS, INLINE THREADS AND COMMENTS (gitoria#44; contract docs/apps-api.md §5, §6). Its own gitoria server(s) and storage, the REAL git binary// over HTTP: GET pulls and pulls/N, POST/GET reviews (current and earlier heads, 409 stale_head, 422 invalid with details, 100 comments, 413), threads (own only, outdated,// paging), replies, resolve, the conversation, seq order, foreign tokens and repos → 404, the organization address, a restart and a second process on the same storage.// node tests/reviews.mjs (GITORIA_REVIEWS_PORT required, the second process takes the next port)import { spawn, spawnSync } from 'node:child_process';import { request as httpRequest } from 'node:http';import { rmSync, mkdirSync, writeFileSync, existsSync } from 'node:fs';import { dirname, join, resolve } from 'node:path';import { fileURLToPath } from 'node:url';const HERE = dirname(fileURLToPath(import.meta.url));const APP = resolve(HERE, '..');const PORT = requiredPort('GITORIA_REVIEWS_PORT'), PORT2 = PORT + 1;const STORE = join(APP, '.scratch', 'reviews-store');const DB = join(STORE, 'db'), GIT = join(STORE, 'git'), WORK = join(STORE, 'work');const BIN = join(APP, 'bin/hybriel');const J = JSON.stringify;let failures = 0, passes = 0;const check = (label, ok, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + String(detail).slice(0, 500)}`); if (ok) passes++; else failures++; };const sleep = (ms) => new Promise(r => setTimeout(r, ms));const env = { ...process.env, GITORIA_STORAGE: DB, GITORIA_GIT: GIT, GITORIA_PORT: String(PORT), GITORIA_WATCH: '0', GITORIA_PUBLIC_URL: `http://gitoria.test:${PORT}`, GITORIA_TICKETS_URL: 'http://127.0.0.1:1' };const HOST = (slug) => `${slug}.gitoria.test`;function raw(method, path, { host, token, body = null, port = PORT, headers = {} } = {}) {return new Promise((res, rej) => {const h = { host: host || HOST('rv'), ...headers };if (token) h.authorization = 'Bearer ' + token;if (body !== null) { h['content-type'] = 'application/json'; h['content-length'] = Buffer.byteLength(body); }const r = httpRequest({ host: '127.0.0.1', port, method, path, headers: h }, (x) => { const c = []; x.on('data', d => c.push(d)); x.on('end', () => { const t = Buffer.concat(c).toString('utf8'); let j = null; try { j = JSON.parse(t); } catch {} res({ status: x.statusCode, headers: x.headers, text: t, json: j }); }); });r.on('error', rej); if (body !== null) r.write(body); r.end();});}const code = (r) => r.json && r.json.error && r.json.error.code;const api = (token, method, path, obj, o = {}) => raw(method, path, { token, body: obj === undefined ? null : (typeof obj === 'string' ? obj : J(obj)), ...o });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]' };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() }; };const must = (cwd, args) => { const r = git(cwd, args); if (!r.ok) throw new Error('git ' + args.join(' ') + ': ' + r.err); return r.out; };const commitAll = (cwd, msg) => { must(cwd, ['add', '-A']); must(cwd, ['commit', '-q', '-m', msg]); return must(cwd, ['rev-parse', 'HEAD']); };const lines = (n, f = (i) => `line ${i}`) => Array.from({ length: n }, (_, i) => f(i + 1)).join('\n') + '\n';const servers = [];const startServer = (port) => { const p = spawn(BIN, ['project.hl'], { cwd: APP, env: { ...env, GITORIA_PORT: String(port) }, stdio: ['ignore', 'pipe', 'pipe'] }); p.log = ''; p.stdout.on('data', d => p.log += d); p.stderr.on('data', d => p.log += d); servers.push(p); return p; };const up = async (p, port) => { for (let i = 0; i < 960; i++) { if (p.exitCode !== null) throw new Error('server exited\n' + p.log); try { if ((await raw('GET', '/api/repos', { host: 'gitoria.test', port })).status === 200) return; } catch {} await sleep(250); } throw new Error('server did not come up\n' + p.log); };const stopAll = async () => { for (const p of servers.splice(0)) { try { p.kill('SIGTERM'); await new Promise(r => { p.once('exit', r); setTimeout(r, 5000); }); } catch {} } };process.on('exit', () => { for (const p of servers) { try { p.kill('SIGTERM'); } catch {} } });try {if (!existsSync(BIN)) throw new Error('bin/hybriel missing');rmSync(STORE, { recursive: true, force: true }); mkdirSync(DB, { recursive: true }); mkdirSync(GIT, { recursive: true }); mkdirSync(WORK, { recursive: true });const seed = spawnSync(BIN, ['tests/reviews-seed.hl'], { cwd: APP, env, encoding: 'utf8' });const TOKEN = (/TOKEN (gtr_[0-9a-f]{40})/.exec(seed.stdout) || [])[1];const T = Object.fromEntries([...seed.stdout.matchAll(/APP (\w+) (gat_[0-9a-f]{40})/g)].map(m => [m[1], m[2]]));const RID = Object.fromEntries([...seed.stdout.matchAll(/REPO (\w+) (\w+)/g)].map(m => [m[1], m[2]]));check('seed: a push token, three apps on rv/other/acme, ids', !!TOKEN && !!T.Alpha && !!T.Beta && !!T.Gamma && !!T.Delta && !!RID.rv, seed.stdout + seed.stderr);if (!TOKEN) throw new Error('no seed');const s1 = startServer(PORT); await up(s1, PORT);const url = (host, path) => `http://app:${TOKEN}@${HOST(host)}:${PORT}/${path}`;const res = (host) => ['-c', `http.curloptResolve=${HOST(host)}:${PORT}:127.0.0.1`];const push = (cwd, host, path, refs) => git(cwd, [...res(host), 'push', url(host, path), ...refs]);// ---- the repo rv: main with a.txt (30 lines), b.txt (10), old.txt (5), keep.txt; PR #1 = f1: edit a.txt:15, new file new.txt (5 lines), rename b.txt → c.txt with line 5 edited, delete old.txtconst W = join(WORK, 'w'); mkdirSync(W);must(W, ['init', '-q', '-b', 'main']);writeFileSync(join(W, 'a.txt'), lines(30)); writeFileSync(join(W, 'b.txt'), lines(10, i => `bee ${i} is a long enough line to be a rename`)); writeFileSync(join(W, 'old.txt'), lines(5)); writeFileSync(join(W, 'keep.txt'), lines(3));commitAll(W, 'base');check('push main to rv', push(W, 'rv', 'rv.git', ['main']).ok);must(W, ['checkout', '-q', '-b', 'f1']);writeFileSync(join(W, 'a.txt'), lines(30, i => i === 15 ? 'line 15 CHANGED' : `line ${i}`)); writeFileSync(join(W, 'new.txt'), lines(5, i => `new ${i}`)); writeFileSync(join(W, 'my file.txt'), lines(5, i => `space ${i}`));must(W, ['mv', 'b.txt', 'c.txt']); writeFileSync(join(W, 'c.txt'), lines(10, i => i === 5 ? 'bee 5 EDITED' : `bee ${i} is a long enough line to be a rename`)); must(W, ['rm', '-q', 'old.txt']);must(W, ['add', '-A']); must(W, ['commit', '-q', '-m', '|||PR first thing', '-m', 'Body of one.']);const h1 = must(W, ['rev-parse', 'HEAD']);check('push the |||PR branch f1 (PR #1)', push(W, 'rv', 'rv.git', ['f1']).ok);must(W, ['checkout', '-q', 'main']); must(W, ['checkout', '-q', '-b', 'f2']); writeFileSync(join(W, 'two.txt'), lines(4, i => `two ${i}`));must(W, ['add', '-A']); must(W, ['commit', '-q', '-m', '|||PR|main] second thing']);check('push the |||PR branch f2 (PR #2)', push(W, 'rv', 'rv.git', ['f2']).ok);// the repo `other` with its own PR #1 (a foreign repo for the foreign-token checks)const O = join(WORK, 'o'); mkdirSync(O); must(O, ['init', '-q', '-b', 'main']); writeFileSync(join(O, 'x.txt'), lines(5)); commitAll(O, 'base');push(O, 'other', 'other.git', ['main']); must(O, ['checkout', '-q', '-b', 'g1']); writeFileSync(join(O, 'x.txt'), lines(5, i => `x ${i}`)); must(O, ['add', '-A']); must(O, ['commit', '-q', '-m', '|||PR other thing']);check('push repo other with a PR', push(O, 'other', 'other.git', ['g1']).ok);// ---- 1. who may askconst A = T.Alpha, B = T.Beta;let r = await api(undefined, 'GET', '/api/pulls');check('no token → 401 unauthorized, in the error shape', r.status === 401 && code(r) === 'unauthorized' && r.json.error.message && 'details' in r.json.error, r.text);r = await api('gat_' + 'a'.repeat(40), 'GET', '/api/pulls');check('an unknown token → 401', r.status === 401 && code(r) === 'unauthorized');for (const [m, p] of [['GET', '/api/pulls/1'], ['GET', '/api/pulls/1/reviews'], ['GET', '/api/pulls/1/threads'], ['GET', '/api/pulls/1/comments'], ['POST', '/api/pulls/1/comments'], ['POST', '/api/pulls/1/reviews']]) {const x = await api(T.Gamma, m, p, m === 'POST' ? { body: 'x', head: h1, verdict: 'comment' } : undefined);check(`${m} ${p} with the token of another repo's app → 404 not_found`, x.status === 404 && code(x) === 'not_found', x.status + x.text);}r = await api(A, 'GET', '/api/pulls', undefined, { host: HOST('other') });check('the token of rv on the address of other → 404', r.status === 404 && code(r) === 'not_found');r = await api(T.Gamma, 'GET', '/api/pulls', undefined, { host: HOST('other') });check('Gamma on its own repo works and sees only that repo\'s PR', r.status === 200 && r.json.pulls.length === 1 && r.json.pulls[0].title === 'other thing', r.text);r = await api(A, 'POST', '/api/pulls');check('POST on the list route → 405 in the error shape', r.status === 405 && !!code(r));// ---- 2. pullsr = await api(A, 'GET', '/api/pulls');const nums = r.json && r.json.pulls ? r.json.pulls.map(p => p.number) : null;check('GET pulls: both open PRs, newest first, next null', r.status === 200 && J(nums) === '[2,1]' && r.json.next === null, r.text);check('GET pulls: the pull object (title, head, ref, baseRef, mergeBase, state, author)', (() => { const p = r.json.pulls[1]; return p.title === 'first thing' && p.head === h1 && p.ref === 'refs/pull/1/head' && p.baseRef === 'refs/heads/main' && p.state === 'open' && p.draft === false && /^[0-9a-f]{40}$/.test(p.mergeBase) && p.author.name === 'Gate Owner'; })(), r.text);r = await api(A, 'GET', '/api/pulls?limit=1');const c1 = r.json && r.json.next;const r2 = await api(A, 'GET', '/api/pulls?limit=1&cursor=' + encodeURIComponent(c1));check('GET pulls?limit=1: page one is #2 with a cursor, page two is #1 with next null', J(r.json.pulls.map(p => p.number)) === '[2]' && !!c1 && J(r2.json.pulls.map(p => p.number)) === '[1]' && r2.json.next === null, r.text + r2.text);check('GET pulls?state=all and state=open both answer; state=merged → 422', (await api(A, 'GET', '/api/pulls?state=all')).json.pulls.length === 2 && (await api(A, 'GET', '/api/pulls?state=merged')).status === 422);check('GET pulls?cursor=junk → 422 invalid', (await api(A, 'GET', '/api/pulls?cursor=junk')).status === 422);r = await api(A, 'GET', '/api/pulls/1');check('GET pulls/1 = the pull object', r.status === 200 && r.json.number === 1 && r.json.head === h1 && r.json.body === 'Body of one.', r.text);check('GET pulls/99 and pulls/abc and pulls/01 → 404', (await api(A, 'GET', '/api/pulls/99')).status === 404 && (await api(A, 'GET', '/api/pulls/abc')).status === 404 && (await api(A, 'GET', '/api/pulls/01')).status === 404);// ---- 3. a review on the current headconst good = [{ path: 'a.txt', line: 15, body: 'changed line' }, { path: 'my file.txt', line: 3, body: 'a file with a space' }, { path: 'c.txt', line: 5, body: 'on the renamed file, new path' }];r = await api(A, 'POST', '/api/pulls/1/reviews', { head: h1, verdict: 'request_changes', body: 'Please fix.', comments: good });check('POST reviews: 201 { review { id verdict head created }, threads [{ id path line }] }', r.status === 201 && r.json.review.verdict === 'request_changes' && r.json.review.head === h1 && !!r.json.review.id && /Z$/.test(r.json.review.created) && r.json.threads.length === 3 && r.json.threads[0].path === 'a.txt' && r.json.threads[0].line === 15 && !!r.json.threads[0].id, r.text);check('F2 inline review preserves a filename with a space', r.status === 201 && r.json.threads[1].path === 'my file.txt' && r.json.threads[1].line === 3, r.status + r.text);const threads1 = r.json.threads;// every line kind: context (above and below the change), added, the edges of the hunkconst edge = await api(A, 'POST', '/api/pulls/1/reviews', { head: h1, verdict: 'comment', body: '', comments: [12, 14, 15, 16, 18].map(l => ({ path: 'a.txt', line: l, body: 'l' + l })).concat([{ path: 'new.txt', line: 5, body: 'last' }, { path: 'c.txt', line: 2, body: 'ctx' }, { path: 'c.txt', line: 8, body: 'ctx' }]) });check('lines: context (12, 14, 16, 18), the added line (15), the last line of a new file, hunk edges of the rename are all accepted', edge.status === 201 && edge.json.threads.length === 8, edge.text);const before = (await api(A, 'GET', '/api/pulls/1/threads?limit=100')).json;const bad = await api(A, 'POST', '/api/pulls/1/reviews', { head: h1, verdict: 'comment', body: 'x', comments: [{ path: 'a.txt', line: 15, body: 'ok' }, { path: 'a.txt', line: 19, body: 'one past the hunk' }, { path: 'nope.txt', line: 1, body: 'no file' }, { path: 'old.txt', line: 1, body: 'deleted file' }, { path: 'keep.txt', line: 1, body: 'unchanged file' }, { path: 'a.txt', line: 11, body: 'one before' }, { path: 'b.txt', line: 5, body: 'old name of the rename' }] });const det = bad.json && bad.json.error && bad.json.error.details;check('a bad line → the WHOLE review 422 invalid with details [{ index path line reason }]', bad.status === 422 && code(bad) === 'invalid' && Array.isArray(det) && det.length === 6 && det.every(d => 'index' in d && 'path' in d && 'line' in d), bad.text);check('details: line_not_in_diff for a.txt 19 and 11; no_such_file for nope, deleted old.txt, unchanged keep.txt, the old rename path', J(det.map(d => [d.index, d.reason])) === J([[1, 'line_not_in_diff'], [2, 'no_such_file'], [3, 'no_such_file'], [4, 'no_such_file'], [5, 'line_not_in_diff'], [6, 'no_such_file']]), J(det));const after = (await api(A, 'GET', '/api/pulls/1/threads?limit=100')).json;const revs = (await api(A, 'GET', '/api/pulls/1/reviews')).json;check('the refused review stored nothing: no new review, no new thread', after.threads.length === before.threads.length && revs.reviews.length === 2, `${after.threads.length} ${before.threads.length} ${revs.reviews.length}`);check('a malformed comment (line 0, 1.5, text; empty body; no path) → 422 invalid with its index', await (async () => { const x = await api(A, 'POST', '/api/pulls/1/reviews', { head: h1, verdict: 'comment', comments: [{ path: 'a.txt', line: 0, body: 'x' }, { path: 'a.txt', line: 1.5, body: 'x' }, { path: 'a.txt', line: '15', body: 'x' }, { path: 'a.txt', line: 15, body: '' }, { line: 15, body: 'x' }] }); return x.status === 422 && code(x) === 'invalid' && x.json.error.details.length === 5 && x.json.error.details.every((d, i) => d.index === i); })());const m = async (patch) => api(A, 'POST', '/api/pulls/1/reviews', { head: h1, verdict: 'comment', body: 'b', ...patch });check('verdict missing / unknown, head missing → 422 invalid', (await m({ verdict: 'lgtm' })).status === 422 && (await m({ verdict: undefined })).status === 422 && (await m({ head: undefined })).status === 422);r = await m({ head: 'f'.repeat(40) });check('a sha that was never a head → 409 stale_head, nothing stored', r.status === 409 && code(r) === 'stale_head' && (await api(A, 'GET', '/api/pulls/1/reviews')).json.reviews.length === 2, r.text);check('a head that is not a sha at all (text, number) → 409 / 422', (await m({ head: 'main' })).status === 409 && (await m({ head: 5 })).status === 422);check('a review body of exactly 65,536 characters is stored, 65,537 → 422', (await m({ body: 'x'.repeat(65536) })).status === 201 && (await m({ body: 'x'.repeat(65537) })).status === 422);check('an inline comment body of 65,537 characters → 422', (await m({ comments: [{ path: 'a.txt', line: 15, body: 'x'.repeat(65537) }] })).status === 422);check('101 inline comments → 422 invalid, nothing stored', (await m({ comments: Array.from({ length: 101 }, () => ({ path: 'a.txt', line: 15, body: 'c' })) })).status === 422);r = await m({ comments: Array.from({ length: 100 }, (_, i) => ({ path: 'a.txt', line: 12 + (i % 7), body: 'c' + i })) });check('100 inline comments → 201 with 100 threads', r.status === 201 && r.json.threads.length === 100, r.status + r.text.slice(0, 200));check('a request body over 1 MB → 413 too_large', await (async () => { const x = await api(A, 'POST', '/api/pulls/1/reviews', J({ head: h1, verdict: 'comment', body: 'y'.repeat(1100000) })); return x.status === 413 && code(x) === 'too_large'; })());check('invalid JSON → 400 invalid_json (a body that is no object; a cut-off one)', code(await api(A, 'POST', '/api/pulls/1/reviews', '[1,2]')) === 'invalid_json' && code(await api(A, 'POST', '/api/pulls/1/reviews', '{"head":')) === 'invalid_json' && code(await api(A, 'POST', '/api/pulls/1/comments', '')) === 'invalid_json');check('review of an unknown PR → 404', (await api(A, 'POST', '/api/pulls/9/reviews', { head: h1, verdict: 'comment' })).status === 404);// ---- 4. an earlier head: the PR moves, the old threads are outdated, a review on the old head still works and is outdated at oncemust(W, ['checkout', '-q', 'f1']); writeFileSync(join(W, 'new.txt'), lines(10, i => `new ${i}`)); const h2 = commitAll(W, 'more lines in new.txt');check('push f1 again (a new head)', push(W, 'rv', 'rv.git', ['f1']).ok);r = await api(A, 'GET', '/api/pulls/1');check('GET pulls/1: the head is the new one', r.json.head === h2, r.text);let ths = (await api(A, 'GET', '/api/pulls/1/threads?limit=100')).json;check('threads written on the old head are outdated now (computed: thread.head != current head)', ths.threads.length === 100 && ths.threads.every(t => t.head === h1 && t.outdated === true), J(ths.threads.slice(0, 1)));r = await api(A, 'POST', '/api/pulls/1/reviews', { head: h1, verdict: 'comment', body: 'on the old head', comments: [{ path: 'new.txt', line: 8, body: 'only on head 2' }] });check('a line that only exists in the NEW head is refused on the old head (the check uses the diff of that head)', r.status === 422 && r.json.error.details[0].reason === 'line_not_in_diff', r.text);r = await api(A, 'POST', '/api/pulls/1/reviews', { head: h1, verdict: 'comment', body: 'on the old head', comments: [{ path: 'new.txt', line: 3, body: 'old head, line 3' }] });check('a review on an earlier head → 201 (not 409)', r.status === 201 && r.json.review.head === h1 && r.json.threads.length === 1, r.text);const oldT = r.json.threads[0].id;r = await api(A, 'POST', '/api/pulls/1/reviews', { head: h2, verdict: 'comment', body: 'on the current head', comments: [{ path: 'new.txt', line: 8, body: 'now line 8 exists' }] });check('the same line 8 is fine on the current head', r.status === 201 && r.json.review.head === h2, r.text);const newT = r.json.threads[0].id;// find the two threads by paging through allconst all = []; let cur = null, pages = 0;do { const x = await api(A, 'GET', '/api/pulls/1/threads?limit=40' + (cur ? '&cursor=' + encodeURIComponent(cur) : '')); all.push(...x.json.threads); cur = x.json.next; pages++; } while (cur && pages < 20);const byId = Object.fromEntries(all.map(t => [t.id, t]));check('paging with limit=40 reads all 113 own threads (3 + 8 + 100 + 2) in 3 pages, no thread twice', all.length === 113 && pages === 3 && new Set(all.map(t => t.id)).size === 113, `${all.length} ${pages}`);check('the thread of the review on the old head is outdated at once, the one on the current head is not', byId[oldT].outdated === true && byId[newT].outdated === false && byId[newT].head === h2 && byId[oldT].head === h1);const seqs = all.map(t => t.comments[0].seq);check('threads come in seq order (the seq of their first comment, strictly increasing)', seqs.every((s, i) => i === 0 || s > seqs[i - 1]), J(seqs.slice(0, 12)));check('a thread: { id path line head outdated resolved comments[{ id seq author{type id name} body created }] }', (() => { const t = byId[threads1[0].id]; const c = t.comments[0]; return t.path === 'a.txt' && t.line === 15 && t.resolved === false && c.author.type === 'app' && c.author.name === 'Alpha' && !!c.author.id && c.body === 'changed line' && Number.isInteger(c.seq) && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(c.created) && typeof c.id === 'string'; })(), J(byId[threads1[0].id]));// ---- 5. reviews list: own, newest first, pagedr = await api(A, 'GET', '/api/pulls/1/reviews');check('GET reviews: own reviews newest first, { id verdict head body created }', r.status === 200 && r.json.reviews.length === 6 && r.json.reviews[0].body === 'on the current head' && r.json.reviews[1].body === 'on the old head' && r.json.reviews[r.json.reviews.length - 1].verdict === 'request_changes' && r.json.reviews[r.json.reviews.length - 1].body === 'Please fix.' && Object.keys(r.json.reviews[0]).sort().join() === 'body,created,head,id,verdict', r.text.slice(0, 400));const rv = []; cur = null; pages = 0;do { const x = await api(A, 'GET', '/api/pulls/1/reviews?limit=2' + (cur ? '&cursor=' + encodeURIComponent(cur) : '')); rv.push(...x.json.reviews); cur = x.json.next; pages++; } while (cur && pages < 20);check('reviews paged by 2 give the same list as one call, no review twice', J(rv.map(x => x.id)) === J(r.json.reviews.map(x => x.id)) && pages === Math.ceil(r.json.reviews.length / 2), `${rv.length}/${r.json.reviews.length} ${pages}`);// Beta: nothing of Alpha's is visibler = await api(B, 'GET', '/api/pulls/1/reviews');check('Beta sees none of Alpha\'s reviews or threads', r.json.reviews.length === 0 && (await api(B, 'GET', '/api/pulls/1/threads')).json.threads.length === 0);r = await api(B, 'POST', '/api/pulls/1/reviews', { head: h2, verdict: 'approve', body: 'Beta approves', comments: [{ path: 'a.txt', line: 15, body: 'beta thread' }] });const betaT = r.json.threads[0].id;check('Beta posts its own review and thread', r.status === 201 && (await api(B, 'GET', '/api/pulls/1/threads')).json.threads.length === 1 && (await api(B, 'GET', '/api/pulls/1/reviews')).json.reviews.length === 1);check('Alpha\'s threads do not include Beta\'s', (await api(A, 'GET', '/api/pulls/1/threads?limit=100')).json.next !== null && !(await api(A, 'GET', '/api/pulls/1/threads?limit=100')).json.threads.some(t => t.id === betaT));// ---- 6. replies, resolve; foreign things are 404const t0 = threads1[0].id;r = await api(A, 'POST', `/api/pulls/1/threads/${t0}/replies`, { body: 'a reply' });check('POST replies → 201 { comment { id seq author body created } } by the app', r.status === 201 && r.json.comment.body === 'a reply' && r.json.comment.author.type === 'app' && r.json.comment.author.name === 'Alpha' && Number.isInteger(r.json.comment.seq), r.text);const replySeq = r.json.comment.seq;check('the thread now has its first comment and the reply, in seq order', await (async () => { const t = (await api(A, 'GET', '/api/pulls/1/threads?limit=1')).json.threads[0]; return t.id === t0 && t.comments.length === 2 && t.comments[1].body === 'a reply' && t.comments[1].seq > t.comments[0].seq; })());check('Beta replies to / resolves Alpha\'s thread → 404 not_found', (await api(B, 'POST', `/api/pulls/1/threads/${t0}/replies`, { body: 'x' })).status === 404 && code(await api(B, 'POST', `/api/pulls/1/threads/${t0}/resolve`, { resolved: true })) === 'not_found');check('Gamma (another repo) replies to Alpha\'s thread → 404', (await api(T.Gamma, 'POST', `/api/pulls/1/threads/${t0}/replies`, { body: 'x' }, { host: HOST('other') })).status === 404);check('Alpha on the wrong PR number (2) or an unknown thread id → 404', (await api(A, 'POST', `/api/pulls/2/threads/${t0}/replies`, { body: 'x' })).status === 404 && (await api(A, 'POST', '/api/pulls/1/threads/nope/replies', { body: 'x' })).status === 404 && (await api(A, 'POST', '/api/pulls/1/threads/nope/resolve', { resolved: true })).status === 404);check('a reply with an empty or too long body → 422', (await api(A, 'POST', `/api/pulls/1/threads/${t0}/replies`, { body: '' })).status === 422 && (await api(A, 'POST', `/api/pulls/1/threads/${t0}/replies`, { body: 'x'.repeat(65537) })).status === 422 && (await api(A, 'POST', `/api/pulls/1/threads/${t0}/replies`, {})).status === 422);check('a reply of exactly 65,536 characters is stored', (await api(A, 'POST', `/api/pulls/1/threads/${t0}/replies`, { body: 'z'.repeat(65536) })).status === 201);r = await api(A, 'POST', `/api/pulls/1/threads/${t0}/resolve`, { resolved: true });check('resolve true → 200 { thread } with resolved true', r.status === 200 && r.json.thread.id === t0 && r.json.thread.resolved === true && r.json.thread.comments.length === 3, r.text.slice(0, 300));check('GET threads shows it resolved; resolve false reopens it', (await api(A, 'GET', '/api/pulls/1/threads?limit=1')).json.threads[0].resolved === true && (await api(A, 'POST', `/api/pulls/1/threads/${t0}/resolve`, { resolved: false })).json.thread.resolved === false);check('resolve with a non-boolean or no body → 422', (await api(A, 'POST', `/api/pulls/1/threads/${t0}/resolve`, { resolved: 'yes' })).status === 422 && (await api(A, 'POST', `/api/pulls/1/threads/${t0}/resolve`, {})).status === 422);// ---- 7. the conversation + seq over everythingconst post = async (tok, n, body, host) => api(tok, 'POST', `/api/pulls/${n}/comments`, { body }, host ? { host } : {});const c_a = await post(A, 1, 'first from Alpha'), c_b = await post(B, 1, 'then Beta'), c_c = await post(A, 1, 'Alpha again');check('POST comments → 201 { comment } in the conversation', c_a.status === 201 && c_a.json.comment.body === 'first from Alpha' && c_a.json.comment.author.name === 'Alpha', c_a.text);r = await api(B, 'GET', '/api/pulls/1/comments');check('GET comments: the whole conversation (both apps), oldest first, only conversation comments (no thread comments)', r.status === 200 && J(r.json.comments.map(c => c.body)) === J(['first from Alpha', 'then Beta', 'Alpha again']) && r.json.next === null, r.text);const cm = []; cur = null; pages = 0;do { const x = await api(A, 'GET', '/api/pulls/1/comments?limit=1' + (cur ? '&cursor=' + encodeURIComponent(cur) : '')); cm.push(...x.json.comments); cur = x.json.next; pages++; } while (cur && pages < 10);check('comments paged by 1 give the same three, in order', pages === 3 && J(cm.map(c => c.id)) === J(r.json.comments.map(c => c.id)));const seqOrder = [replySeq, c_a.json.comment.seq, c_b.json.comment.seq, c_c.json.comment.seq];check('seq grows strictly over thread replies and conversation comments (as posted)', seqOrder.every((s, i) => i === 0 || s > seqOrder[i - 1]), J(seqOrder));const p2 = await post(A, 2, 'on PR two');check('seq is per repo over all PRs: a comment on PR #2 is above PR #1\'s', p2.json.comment.seq > c_c.json.comment.seq, J([p2.json.comment.seq, c_c.json.comment.seq]));check('the conversation of PR #2 holds only its own comment; PR #1 is unchanged', (await api(A, 'GET', '/api/pulls/2/comments')).json.comments.length === 1 && (await api(A, 'GET', '/api/pulls/1/comments')).json.comments.length === 3);check('another repo\'s seq is its own count (starts at 1)', (await post(T.Gamma, 1, 'other repo', HOST('other'))).json.comment.seq === 1);check('comment bodies: empty / whitespace / 65,537 → 422, 65,536 → 201', (await post(A, 1, '')).status === 422 && (await post(A, 1, ' ')).status === 422 && (await post(A, 1, 'x'.repeat(65537))).status === 422 && (await post(A, 1, 'x'.repeat(65536))).status === 201);check('Markdown and markup are stored as sent (shown escaped by #45): a <script> body comes back verbatim', (await post(A, 1, '<script>alert(1)</script> **b**')).json.comment.body === '<script>alert(1)</script> **b**');check('GET comments of an unknown PR → 404', (await api(A, 'GET', '/api/pulls/9/comments')).status === 404);// ---- 8. reviews on PR #2 for the current verdict (read by the probe below)for (const v of ['request_changes', 'comment']) await api(A, 'POST', '/api/pulls/2/reviews', { head: (await api(A, 'GET', '/api/pulls/2')).json.head, verdict: v, body: v });// ---- 9. the organization address, both spellingsconst Q = join(WORK, 'q'); mkdirSync(Q); must(Q, ['init', '-q', '-b', 'main']); writeFileSync(join(Q, 'q.txt'), lines(5)); commitAll(Q, 'base');const orgUrl = `http://app:${TOKEN}@acme.gitoria.test:${PORT}/orgrepo.git`; const orgRes = ['-c', `http.curloptResolve=acme.gitoria.test:${PORT}:127.0.0.1`];git(Q, [...orgRes, 'push', orgUrl, 'main']); must(Q, ['checkout', '-q', '-b', 'q1']); writeFileSync(join(Q, 'q.txt'), lines(5, i => `q ${i}`)); must(Q, ['add', '-A']); must(Q, ['commit', '-q', '-m', '|||PR org thing']);const hq = must(Q, ['rev-parse', 'HEAD']); git(Q, [...orgRes, 'push', orgUrl, 'q1']);for (const p of ['/orgrepo/api/pulls', '/api/orgrepo/pulls']) { const x = await api(T.Delta, 'GET', p, undefined, { host: HOST('acme') }); check(`org repo: GET ${p} → its PR`, x.status === 200 && x.json.pulls.length === 1 && x.json.pulls[0].title === 'org thing', x.status + x.text.slice(0, 200)); }r = await api(T.Delta, 'POST', '/orgrepo/api/pulls/1/reviews', { head: hq, verdict: 'approve', comments: [{ path: 'q.txt', line: 1, body: 'org thread' }] }, { host: HOST('acme') });check('org repo: a review with a thread on /<repo>/api/pulls/1/reviews', r.status === 201 && r.json.threads.length === 1, r.text);check('org repo: the token of rv on the org address → 404', (await api(A, 'GET', '/orgrepo/api/pulls', undefined, { host: HOST('acme') })).status === 404);// ---- 9b. the API spellings win over the page routes (live, /api/pulls answered the HTML pulls page: '/:orepo/pulls' with orepo = api), and an unknown API path is the contract's JSON 404for (const [host, tok, p] of [[HOST('rv'), A, '/api/pulls?state=open'], [HOST('rv'), A, '/api/pulls/1'], [HOST('acme'), T.Delta, '/orgrepo/api/pulls?state=open'], [HOST('acme'), T.Delta, '/api/orgrepo/pulls?state=open']]) {const x = await api(tok, 'GET', p, undefined, { host });check(`GET ${p} on ${host.split('.')[0]}: Content-Type application/json, JSON body (not the HTML page)`, x.status === 200 && /^application\/json/.test(x.headers['content-type']) && x.json !== null && !/<html/i.test(x.text), x.status + ' ' + x.headers['content-type']);}for (const [host, p] of [[HOST('rv'), '/api/nope'], [HOST('rv'), '/api/tickets'], [HOST('rv'), '/api/code'], [HOST('rv'), '/api/pulls/1/nonsense'], [HOST('rv'), '/api/releases'], [HOST('acme'), '/orgrepo/api/zzz'], [HOST('acme'), '/api/orgrepo/zzz']]) {const x = await api(A, 'GET', p, undefined, { host });check(`an unknown API path ${p} (${host.split('.')[0]}) → 404 JSON { error { code not_found, message, details null } }`, x.status === 404 && /^application\/json/.test(x.headers['content-type']) && x.json && x.json.error && x.json.error.code === 'not_found' && !!x.json.error.message && x.json.error.details === null, x.status + ' ' + x.text.slice(0, 120));}check('the page routes still answer pages: /pulls of rv and /orgrepo/pulls of acme are HTML 200', await (async () => { const a = await raw('GET', '/pulls', { host: HOST('rv') }), b = await raw('GET', '/orgrepo/pulls', { host: HOST('acme') }); return a.status === 200 && /text\/html/.test(a.headers['content-type']) && b.status === 200 && /text\/html/.test(b.headers['content-type']); })());// ---- 10. a restart keeps everything and seq goes on; a second process on the same storage hands out other numbersawait stopAll();const probe = (repo, n, app) => spawnSync(BIN, ['tests/reviews-probe.hl', repo, String(n), app], { cwd: APP, env, encoding: 'utf8' }).stdout.trim();check('current verdict: Alpha on PR #2 gave request_changes, then a comment review → still request_changes (a comment does not clear it)', /^verdict request_changes /.test(probe(RID.rv, 2, 'Alpha')), probe(RID.rv, 2, 'Alpha'));check('current verdict: Beta on PR #1 = approve; Alpha on PR #1 = its latest approve/request_changes (request_changes); Beta on PR #2 = none', /^verdict approve /.test(probe(RID.rv, 1, 'Beta')) && /^verdict request_changes /.test(probe(RID.rv, 1, 'Alpha')) && probe(RID.rv, 2, 'Beta') === 'verdict none');const s2 = startServer(PORT); await up(s2, PORT);const top = (await api(A, 'GET', '/api/pulls/1/comments?limit=100')).json.comments;check('after a restart the data is there', top.length === 5 && top[0].body === 'first from Alpha', J(top.map(c => c.body)));const afterRestart = (await post(A, 1, 'after the restart')).json.comment.seq;check('after a restart the next seq is above every earlier one', afterRestart > Math.max(...top.map(c => c.seq)) && afterRestart > p2.json.comment.seq, `${afterRestart}`);const s3 = startServer(PORT2); await up(s3, PORT2);const got = [];for (let i = 0; i < 6; i++) { const x = await api(A, 'POST', '/api/pulls/1/comments', { body: 'two procs ' + i }, { port: i % 2 ? PORT2 : PORT }); got.push([i % 2, x.json && x.json.comment ? x.json.comment.seq : null]); }const only = got.map(g => g[1]);check('two processes on one storage (a deploy swap): six comments, six different seq numbers', only.every(Number.isInteger) && new Set(only).size === 6, J(got));check('each process\'s own numbers grow', [0, 1].every(k => { const s = got.filter(g => g[0] === k).map(g => g[1]); return s.every((v, i) => i === 0 || v > s[i - 1]); }), J(got));check('both processes\' numbers are above the earlier ones', Math.min(...only) > afterRestart, J(got));// The seeded apps point at https://x.worldapi.org/hook, which does not resolve; their failed deliveries are expected, not server errors.const errLog = (s2.log + s3.log).split('\n').filter(l => !l.includes('https://x.worldapi.org/hook: could not resolve host')).join('\n');check('no server error was logged', !/error absorbed|startup error/.test(errLog), errLog.split('\n').filter(l => /error/i.test(l)).slice(0, 5).join('|'));} catch (e) {failures++; console.log('FAIL gate crashed — ' + (e && e.stack || e));} finally {await stopAll();}console.log(`\n${passes} passed, ${failures} failed`);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