stoke/test/cli.test.js

373 lines
14 KiB
JavaScript
Raw Normal View History

Audit: fix auth/config bugs, add issue/pr create, tests and docs Fixes found during a full audit of the CLI: - auth logout: remote token revocation always failed with 401 because Forgejo only accepts Basic auth on the token endpoints. Logout now asks for (or accepts) the account password, supports --password, --password-file and --local-only, and clearly reports when the token is left active. - Silent password prompt actually echoed the password on a TTY: overriding rl.write does not suppress readline echo. Switched to the callback readline module and mute _writeToOutput instead (the readline/promises interface does not honor that hook). - Global --config flag was silently ignored: config paths were resolved at require time, before the preAction hook set STOKE_CONFIG_FILE. Paths are now resolved lazily on every access. - XDG_CONFIG_HOME handling put the config in $XDG_CONFIG_HOME/.config/stoke; per the XDG spec it now resolves to $XDG_CONFIG_HOME/stoke. - repo create: --auto-init defaulted to true with no way to disable it; added --no-auto-init. - repo import/import-batch: a GitHub token was required even for non-GitHub services (e.g. --service git), making those imports fail without gh/GITHUB_TOKEN. Tokens are now only auto-resolved for the github service; batch imports resolve per entry and memoize. - Branding leftovers: 'Run: forgejo auth login' hint and forgejo-cli/1.0.0 User-Agent now say stoke (UA tracks pkg.version). - Added request timeouts (30s default, 10m for migrations). - --limit and --team-id are validated as integers instead of silently misbehaving on garbage (NaN made -l show all results). New commands (per the repo's every-operation-becomes-a-command design): - stoke issue create (title/body/body-file/assignees) - stoke pr create (head/base/title/body/body-file) Tests and metadata: - New test suite on the built-in node:test runner (25 tests) covering config resolution/persistence, the API client with a mocked fetch, and end-to-end CLI behavior. npm test previously matched no files. - package.json: engines >=22.12.0 (required by commander@15 — the README claimed Node 18), repository, keywords, author; version 1.1.0. - README: corrected Node requirement, documented repo rename (was missing), issue create, pr create, logout options and revocation caveat, --no-auto-init, XDG behavior, import token rules, testing. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-22 19:28:23 +00:00
const { test } = require('node:test');
const assert = require('node:assert/strict');
const { execFileSync, spawn, spawnSync } = require('node:child_process');
Audit: fix auth/config bugs, add issue/pr create, tests and docs Fixes found during a full audit of the CLI: - auth logout: remote token revocation always failed with 401 because Forgejo only accepts Basic auth on the token endpoints. Logout now asks for (or accepts) the account password, supports --password, --password-file and --local-only, and clearly reports when the token is left active. - Silent password prompt actually echoed the password on a TTY: overriding rl.write does not suppress readline echo. Switched to the callback readline module and mute _writeToOutput instead (the readline/promises interface does not honor that hook). - Global --config flag was silently ignored: config paths were resolved at require time, before the preAction hook set STOKE_CONFIG_FILE. Paths are now resolved lazily on every access. - XDG_CONFIG_HOME handling put the config in $XDG_CONFIG_HOME/.config/stoke; per the XDG spec it now resolves to $XDG_CONFIG_HOME/stoke. - repo create: --auto-init defaulted to true with no way to disable it; added --no-auto-init. - repo import/import-batch: a GitHub token was required even for non-GitHub services (e.g. --service git), making those imports fail without gh/GITHUB_TOKEN. Tokens are now only auto-resolved for the github service; batch imports resolve per entry and memoize. - Branding leftovers: 'Run: forgejo auth login' hint and forgejo-cli/1.0.0 User-Agent now say stoke (UA tracks pkg.version). - Added request timeouts (30s default, 10m for migrations). - --limit and --team-id are validated as integers instead of silently misbehaving on garbage (NaN made -l show all results). New commands (per the repo's every-operation-becomes-a-command design): - stoke issue create (title/body/body-file/assignees) - stoke pr create (head/base/title/body/body-file) Tests and metadata: - New test suite on the built-in node:test runner (25 tests) covering config resolution/persistence, the API client with a mocked fetch, and end-to-end CLI behavior. npm test previously matched no files. - package.json: engines >=22.12.0 (required by commander@15 — the README claimed Node 18), repository, keywords, author; version 1.1.0. - README: corrected Node requirement, documented repo rename (was missing), issue create, pr create, logout options and revocation caveat, --no-auto-init, XDG behavior, import token rules, testing. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-22 19:28:23 +00:00
const fs = require('node:fs');
const http = require('node:http');
Audit: fix auth/config bugs, add issue/pr create, tests and docs Fixes found during a full audit of the CLI: - auth logout: remote token revocation always failed with 401 because Forgejo only accepts Basic auth on the token endpoints. Logout now asks for (or accepts) the account password, supports --password, --password-file and --local-only, and clearly reports when the token is left active. - Silent password prompt actually echoed the password on a TTY: overriding rl.write does not suppress readline echo. Switched to the callback readline module and mute _writeToOutput instead (the readline/promises interface does not honor that hook). - Global --config flag was silently ignored: config paths were resolved at require time, before the preAction hook set STOKE_CONFIG_FILE. Paths are now resolved lazily on every access. - XDG_CONFIG_HOME handling put the config in $XDG_CONFIG_HOME/.config/stoke; per the XDG spec it now resolves to $XDG_CONFIG_HOME/stoke. - repo create: --auto-init defaulted to true with no way to disable it; added --no-auto-init. - repo import/import-batch: a GitHub token was required even for non-GitHub services (e.g. --service git), making those imports fail without gh/GITHUB_TOKEN. Tokens are now only auto-resolved for the github service; batch imports resolve per entry and memoize. - Branding leftovers: 'Run: forgejo auth login' hint and forgejo-cli/1.0.0 User-Agent now say stoke (UA tracks pkg.version). - Added request timeouts (30s default, 10m for migrations). - --limit and --team-id are validated as integers instead of silently misbehaving on garbage (NaN made -l show all results). New commands (per the repo's every-operation-becomes-a-command design): - stoke issue create (title/body/body-file/assignees) - stoke pr create (head/base/title/body/body-file) Tests and metadata: - New test suite on the built-in node:test runner (25 tests) covering config resolution/persistence, the API client with a mocked fetch, and end-to-end CLI behavior. npm test previously matched no files. - package.json: engines >=22.12.0 (required by commander@15 — the README claimed Node 18), repository, keywords, author; version 1.1.0. - README: corrected Node requirement, documented repo rename (was missing), issue create, pr create, logout options and revocation caveat, --no-auto-init, XDG behavior, import token rules, testing. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-22 19:28:23 +00:00
const os = require('node:os');
const path = require('node:path');
const CLI = path.join(__dirname, '..', 'src', 'cli.js');
const pkg = require('../package.json');
function run(args, env = {}) {
return spawnSync(process.execPath, [CLI, ...args], {
encoding: 'utf8',
env: { ...process.env, ...env },
});
}
test('--version matches package.json', () => {
const out = execFileSync(process.execPath, [CLI, '--version'], { encoding: 'utf8' });
assert.equal(out.trim(), pkg.version);
});
test('--help lists every top-level command', () => {
const out = execFileSync(process.execPath, [CLI, '--help'], { encoding: 'utf8' });
for (const cmd of ['auth', 'repo', 'issue', 'pr', 'release', 'label', 'branch', 'collaborator', 'org', 'user', 'api']) {
Audit: fix auth/config bugs, add issue/pr create, tests and docs Fixes found during a full audit of the CLI: - auth logout: remote token revocation always failed with 401 because Forgejo only accepts Basic auth on the token endpoints. Logout now asks for (or accepts) the account password, supports --password, --password-file and --local-only, and clearly reports when the token is left active. - Silent password prompt actually echoed the password on a TTY: overriding rl.write does not suppress readline echo. Switched to the callback readline module and mute _writeToOutput instead (the readline/promises interface does not honor that hook). - Global --config flag was silently ignored: config paths were resolved at require time, before the preAction hook set STOKE_CONFIG_FILE. Paths are now resolved lazily on every access. - XDG_CONFIG_HOME handling put the config in $XDG_CONFIG_HOME/.config/stoke; per the XDG spec it now resolves to $XDG_CONFIG_HOME/stoke. - repo create: --auto-init defaulted to true with no way to disable it; added --no-auto-init. - repo import/import-batch: a GitHub token was required even for non-GitHub services (e.g. --service git), making those imports fail without gh/GITHUB_TOKEN. Tokens are now only auto-resolved for the github service; batch imports resolve per entry and memoize. - Branding leftovers: 'Run: forgejo auth login' hint and forgejo-cli/1.0.0 User-Agent now say stoke (UA tracks pkg.version). - Added request timeouts (30s default, 10m for migrations). - --limit and --team-id are validated as integers instead of silently misbehaving on garbage (NaN made -l show all results). New commands (per the repo's every-operation-becomes-a-command design): - stoke issue create (title/body/body-file/assignees) - stoke pr create (head/base/title/body/body-file) Tests and metadata: - New test suite on the built-in node:test runner (25 tests) covering config resolution/persistence, the API client with a mocked fetch, and end-to-end CLI behavior. npm test previously matched no files. - package.json: engines >=22.12.0 (required by commander@15 — the README claimed Node 18), repository, keywords, author; version 1.1.0. - README: corrected Node requirement, documented repo rename (was missing), issue create, pr create, logout options and revocation caveat, --no-auto-init, XDG behavior, import token rules, testing. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-22 19:28:23 +00:00
assert.match(out, new RegExp(`^\\s+${cmd}`, 'm'), `missing command: ${cmd}`);
}
});
test('unauthenticated commands fail with a login hint', () => {
const missing = path.join(os.tmpdir(), `stoke-none-${process.pid}.json`);
const res = run(['repo', 'list'], { STOKE_CONFIG_FILE: missing });
assert.equal(res.status, 1);
assert.match(res.stderr, /stoke auth login/);
});
test('global --config flag overrides the config location', () => {
// Point --config at a nonexistent file: auth status must report
// "Not authenticated" instead of silently using the default config.
const missing = path.join(os.tmpdir(), `stoke-missing-${process.pid}.json`);
const res = run(['--config', missing, 'auth', 'status']);
assert.equal(res.status, 0);
assert.match(res.stdout, /Not authenticated/);
});
test('invalid --limit is rejected before any network call', () => {
const res = run(['repo', 'list', '-l', 'abc']);
assert.equal(res.status, 1);
assert.match(res.stderr, /Limit must be a non-negative integer/);
});
test('invalid --team-id is rejected before any network call', () => {
const res = run(['org', 'team', 'member-add', '--team-id', 'zero', '-u', 'x']);
assert.equal(res.status, 1);
assert.match(res.stderr, /Id must be a positive integer/);
});
Add apt distribution: deb packaging, registry publish, docs (#1) Implements #1 — stoke installable with apt-get install stoke. Packaging: - scripts/build-deb.sh: builds dist/stoke_<version>_all.deb from a clean staging copy (src + fresh npm ci --omit=dev), pure-JS Architecture: all, Depends: nodejs (>= 22.12), /usr/lib/stoke payload with /usr/bin/stoke symlink, copyright + changelog, normalized permissions. Lintian-clean. - scripts/publish-deb.sh: uploads a .deb to the Forgejo Debian registry (owner/distribution/component parameterized, defaults heavy-duty/ stable/main), authenticating with STOKE_TOKEN or the stoke login token. - scripts/install-apt.sh: consumer-side one-time setup — adds the registry key and apt source, then apt-get install stoke. Falls back to a [trusted=yes] source when apt's sqv verifier rejects the forge's registry signature (known upstream Forgejo signing bug; the script prefers the signed source so setups heal once the forge is fixed). - .forgejo/workflows/release.yml: on v* tags — test, build, publish to the heavy-duty registry, attach the .deb to the release page. Needs a runner and a RELEASE_TOKEN secret with org package write. New command: - stoke pr merge (-n, --method merge|rebase|rebase-merge|squash, --title, --message, --delete-branch) — gap found while merging !2. Docs and housekeeping: - README: 'Install with apt' as the primary installation method with manual setup and dpkg fallback, signature caveat, pr merge reference, Packaging and releasing section with a release checklist. - dist/ gitignored; version bumped to 1.2.0. Verified end-to-end on this machine: built the deb (lintian-clean), published it to the Forgejo Debian registry, installed it with apt-get install stoke via install-apt.sh, and confirmed the installed CLI works against the live forge. The test upload was removed from the personal namespace afterwards; publishing under heavy-duty needs an org-member token (401 reqPackageAccess with this restricted account). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-22 19:40:51 +00:00
test('pr merge validates --number before any network call', () => {
const res = run(['pr', 'merge', '-o', 'o', '-r', 'r', '-n', 'seven']);
assert.equal(res.status, 1);
assert.match(res.stderr, /Id must be a positive integer/);
});
Audit: fix auth/config bugs, add issue/pr create, tests and docs Fixes found during a full audit of the CLI: - auth logout: remote token revocation always failed with 401 because Forgejo only accepts Basic auth on the token endpoints. Logout now asks for (or accepts) the account password, supports --password, --password-file and --local-only, and clearly reports when the token is left active. - Silent password prompt actually echoed the password on a TTY: overriding rl.write does not suppress readline echo. Switched to the callback readline module and mute _writeToOutput instead (the readline/promises interface does not honor that hook). - Global --config flag was silently ignored: config paths were resolved at require time, before the preAction hook set STOKE_CONFIG_FILE. Paths are now resolved lazily on every access. - XDG_CONFIG_HOME handling put the config in $XDG_CONFIG_HOME/.config/stoke; per the XDG spec it now resolves to $XDG_CONFIG_HOME/stoke. - repo create: --auto-init defaulted to true with no way to disable it; added --no-auto-init. - repo import/import-batch: a GitHub token was required even for non-GitHub services (e.g. --service git), making those imports fail without gh/GITHUB_TOKEN. Tokens are now only auto-resolved for the github service; batch imports resolve per entry and memoize. - Branding leftovers: 'Run: forgejo auth login' hint and forgejo-cli/1.0.0 User-Agent now say stoke (UA tracks pkg.version). - Added request timeouts (30s default, 10m for migrations). - --limit and --team-id are validated as integers instead of silently misbehaving on garbage (NaN made -l show all results). New commands (per the repo's every-operation-becomes-a-command design): - stoke issue create (title/body/body-file/assignees) - stoke pr create (head/base/title/body/body-file) Tests and metadata: - New test suite on the built-in node:test runner (25 tests) covering config resolution/persistence, the API client with a mocked fetch, and end-to-end CLI behavior. npm test previously matched no files. - package.json: engines >=22.12.0 (required by commander@15 — the README claimed Node 18), repository, keywords, author; version 1.1.0. - README: corrected Node requirement, documented repo rename (was missing), issue create, pr create, logout options and revocation caveat, --no-auto-init, XDG behavior, import token rules, testing. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-22 19:28:23 +00:00
test('issue create --body-file reports unreadable files cleanly', () => {
const cfg = path.join(os.tmpdir(), `stoke-cfg-${process.pid}.json`);
fs.writeFileSync(cfg, JSON.stringify({ url: 'https://forge.test', token: 'tok' }));
try {
const res = run(
['issue', 'create', '-o', 'o', '-r', 'r', '-t', 't', '--body-file', '/nonexistent/body.md'],
{ STOKE_CONFIG_FILE: cfg },
);
assert.equal(res.status, 1);
assert.match(res.stderr, /Could not read body file/);
} finally {
fs.unlinkSync(cfg);
}
});
test('pr show validates --number before any network call', () => {
const cfg = path.join(os.tmpdir(), `stoke-cfg-${process.pid}.json`);
fs.writeFileSync(cfg, JSON.stringify({ url: 'https://forge.test', token: 'tok' }));
try {
const res = run(['pr', 'show', '-o', 'o', '-r', 'r', '-n', 'zero'], { STOKE_CONFIG_FILE: cfg });
assert.equal(res.status, 1);
assert.match(res.stderr, /Id must be a positive integer/);
} finally {
fs.unlinkSync(cfg);
}
});
test('pr comment rejects a missing body before any network call', () => {
const cfg = path.join(os.tmpdir(), `stoke-cfg-${process.pid}.json`);
fs.writeFileSync(cfg, JSON.stringify({ url: 'https://forge.test', token: 'tok' }));
try {
const res = run(['pr', 'comment', '-o', 'o', '-r', 'r', '-n', '1'], { STOKE_CONFIG_FILE: cfg });
assert.equal(res.status, 1);
assert.match(res.stderr, /Comment body is required/);
} finally {
fs.unlinkSync(cfg);
}
});
test('pr comment rejects a whitespace-only body before any network call', () => {
const cfg = path.join(os.tmpdir(), `stoke-cfg-${process.pid}.json`);
fs.writeFileSync(cfg, JSON.stringify({ url: 'https://forge.test', token: 'tok' }));
try {
const res = run(['pr', 'comment', '-o', 'o', '-r', 'r', '-n', '1', '-b', ' '], { STOKE_CONFIG_FILE: cfg });
assert.equal(res.status, 1);
assert.match(res.stderr, /Comment body is required/);
} finally {
fs.unlinkSync(cfg);
}
});
test('pr review rejects an invalid event before any network call', () => {
const cfg = path.join(os.tmpdir(), `stoke-cfg-${process.pid}.json`);
fs.writeFileSync(cfg, JSON.stringify({ url: 'https://forge.test', token: 'tok' }));
try {
const res = run(['pr', 'review', '-o', 'o', '-r', 'r', '-n', '1', '--event', 'nope'], { STOKE_CONFIG_FILE: cfg });
assert.equal(res.status, 1);
assert.match(res.stderr, /Invalid review event/);
} finally {
fs.unlinkSync(cfg);
}
});
test('pr review accepts approved as an alias for approve before any network call', () => {
const cfg = path.join(os.tmpdir(), `stoke-cfg-${process.pid}.json`);
fs.writeFileSync(cfg, JSON.stringify({ url: 'https://forge.test', token: 'tok' }));
try {
// Network fails; must not fail at event validation.
const res = run(['pr', 'review', '-o', 'o', '-r', 'r', '-n', '1', '--event', 'APPROVED'], { STOKE_CONFIG_FILE: cfg });
assert.equal(res.status, 1);
assert.doesNotMatch(res.stderr, /Invalid review event/);
assert.doesNotMatch(res.stderr, /requires a non-empty body/);
} finally {
fs.unlinkSync(cfg);
}
});
test('pr review request-changes rejects a missing body before any network call', () => {
const cfg = path.join(os.tmpdir(), `stoke-cfg-${process.pid}.json`);
fs.writeFileSync(cfg, JSON.stringify({ url: 'https://forge.test', token: 'tok' }));
try {
const res = run(['pr', 'review', '-o', 'o', '-r', 'r', '-n', '1', '--event', 'request-changes'], { STOKE_CONFIG_FILE: cfg });
assert.equal(res.status, 1);
assert.match(res.stderr, /requires a non-empty body/);
} finally {
fs.unlinkSync(cfg);
}
});
test('pr review comment rejects a whitespace-only body before any network call', () => {
const cfg = path.join(os.tmpdir(), `stoke-cfg-${process.pid}.json`);
fs.writeFileSync(cfg, JSON.stringify({ url: 'https://forge.test', token: 'tok' }));
try {
const res = run(['pr', 'review', '-o', 'o', '-r', 'r', '-n', '1', '--event', 'comment', '-b', ' '], { STOKE_CONFIG_FILE: cfg });
assert.equal(res.status, 1);
assert.match(res.stderr, /requires a non-empty body/);
} finally {
fs.unlinkSync(cfg);
}
});
test('pr review approve allows an empty body before any network call', () => {
const cfg = path.join(os.tmpdir(), `stoke-cfg-${process.pid}.json`);
fs.writeFileSync(cfg, JSON.stringify({ url: 'https://forge.test', token: 'tok' }));
try {
const res = run(['pr', 'review', '-o', 'o', '-r', 'r', '-n', '1', '--event', 'approve'], { STOKE_CONFIG_FILE: cfg });
// It fails at the network call, not at validation.
assert.equal(res.status, 1);
assert.doesNotMatch(res.stderr, /requires a non-empty body/);
} finally {
fs.unlinkSync(cfg);
}
});
test('label create rejects an invalid color before any network call', () => {
const res = run(['label', 'create', '-o', 'o', '-r', 'r', '--name', 'x', '--color', 'red']);
assert.equal(res.status, 1);
assert.match(res.stderr, /Color must be 6 hex digits/);
});
test('label delete requires one of --id or --name before any network call', () => {
const res = run(['label', 'delete', '-o', 'o', '-r', 'r']);
assert.equal(res.status, 1);
assert.match(res.stderr, /One of --id or --name is required/);
});
test('api rejects an endpoint without a leading slash before any network call', () => {
const res = run(['api', 'repos/o/r']);
assert.equal(res.status, 1);
assert.match(res.stderr, /Endpoint must start with \//);
});
test('api rejects an unsupported method before any network call', () => {
const res = run(['api', '/user', '-X', 'HEAD']);
assert.equal(res.status, 1);
assert.match(res.stderr, /Unsupported method/);
});
test('api rejects --paginate with a non-GET method before any network call', () => {
const res = run(['api', '/user', '-X', 'POST', '--paginate']);
assert.equal(res.status, 1);
assert.match(res.stderr, /--paginate only works with GET/);
});
test('api rejects invalid JSON input before any network call', () => {
const res = run(['api', '/user', '--input', '{nope']);
assert.equal(res.status, 1);
assert.match(res.stderr, /not valid JSON/);
});
test('api sends the token and prints the JSON response', async () => {
const cfg = path.join(os.tmpdir(), `stoke-cfg-${process.pid}-api.json`);
const TIMEOUT_MS = 5000;
let timer;
const result = await new Promise((resolve, reject) => {
const fail = (err) => {
clearTimeout(timer);
try { server.close(); } catch { /* already closed */ }
reject(err instanceof Error ? err : new Error(String(err)));
};
let authHeader = null;
const server = http.createServer((req, res) => {
authHeader = req.headers.authorization;
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ login: 'bot' }));
});
timer = setTimeout(() => fail(new Error('timeout')), TIMEOUT_MS);
server.listen(0, '127.0.0.1', async () => {
const { port } = server.address();
fs.writeFileSync(cfg, JSON.stringify({ url: `http://127.0.0.1:${port}`, token: 'tok' }));
try {
const res = await spawnAsync(['api', '/user'], { STOKE_CONFIG_FILE: cfg });
clearTimeout(timer);
server.close(() => resolve({ res, authHeader }));
} catch (err) {
fail(err);
}
});
}).finally(() => clearTimeout(timer));
try {
assert.equal(result.res.status, 0, result.res.stderr);
assert.equal(result.authHeader, 'token tok');
assert.deepEqual(JSON.parse(result.res.stdout), { login: 'bot' });
} finally {
fs.unlinkSync(cfg);
}
});
function spawnAsync(args, env = {}) {
return new Promise((resolve, reject) => {
const child = spawn(process.execPath, [CLI, ...args], {
env: { ...process.env, ...env },
});
let stdout = '';
let stderr = '';
child.stdout.setEncoding('utf8');
child.stderr.setEncoding('utf8');
child.stdout.on('data', (chunk) => { stdout += chunk; });
child.stderr.on('data', (chunk) => { stderr += chunk; });
child.on('error', reject);
child.on('close', (status) => resolve({ status, stdout, stderr }));
});
}
test('pr review preserves exact body-file whitespace through the CLI boundary', async () => {
const cfg = path.join(os.tmpdir(), `stoke-cfg-${process.pid}.json`);
const bodyFile = path.join(os.tmpdir(), `stoke-body-${process.pid}.md`);
const rawBody = ' leading spaces\nline\ntrailing newline\n';
fs.writeFileSync(bodyFile, rawBody, 'utf8');
const TIMEOUT_MS = 5000;
let timer;
const captured = await new Promise((resolve, reject) => {
const fail = (err) => {
clearTimeout(timer);
try { server.close(); } catch { /* already closed */ }
reject(err instanceof Error ? err : new Error(String(err)));
};
const server = http.createServer((req, res) => {
let data = '';
req.setEncoding('utf8');
req.on('data', (chunk) => { data += chunk; });
req.on('end', () => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ id: 99, html_url: 'https://forge.test/reviews/99' }));
clearTimeout(timer);
server.close(() => resolve({ url: req.url, body: data, cliStatus: null }));
});
});
timer = setTimeout(() => fail(new Error(`CLI boundary test timed out after ${TIMEOUT_MS}ms`)), TIMEOUT_MS);
server.listen(0, '127.0.0.1', async () => {
const { port } = server.address();
fs.writeFileSync(cfg, JSON.stringify({ url: `http://127.0.0.1:${port}`, token: 'tok' }));
try {
const res = await spawnAsync(
['pr', 'review', '-o', 'o', '-r', 'r', '-n', '7', '--event', 'request-changes', '--body-file', bodyFile],
{ STOKE_CONFIG_FILE: cfg },
);
if (res.status !== 0) {
fail(new Error(`CLI failed (status ${res.status}): ${res.stderr}`));
return;
}
// Capture is resolved from the HTTP handler; assert exit 0 here via side channel.
// If the handler already resolved, attach status for the outer asserts.
} catch (err) {
fail(err);
}
});
}).finally(() => clearTimeout(timer));
try {
assert.equal(captured.url, '/api/v1/repos/o/r/pulls/7/reviews');
const json = JSON.parse(captured.body);
assert.equal(json.event, 'REQUEST_CHANGES');
assert.equal(json.body, rawBody);
} finally {
fs.unlinkSync(cfg);
fs.unlinkSync(bodyFile);
}
});
test('pr review prints the review URL from the API response', async () => {
const cfg = path.join(os.tmpdir(), `stoke-cfg-${process.pid}-url.json`);
const TIMEOUT_MS = 5000;
let timer;
const result = await new Promise((resolve, reject) => {
const fail = (err) => {
clearTimeout(timer);
try { server.close(); } catch { /* already closed */ }
reject(err instanceof Error ? err : new Error(String(err)));
};
const server = http.createServer((req, res) => {
let data = '';
req.on('data', (c) => { data += c; });
req.on('end', () => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ id: 42, html_url: 'https://forge.test/pulls/7#issuecomment-42' }));
});
});
timer = setTimeout(() => fail(new Error('timeout')), TIMEOUT_MS);
server.listen(0, '127.0.0.1', async () => {
const { port } = server.address();
fs.writeFileSync(cfg, JSON.stringify({ url: `http://127.0.0.1:${port}`, token: 'tok' }));
try {
const res = await spawnAsync(
['pr', 'review', '-o', 'o', '-r', 'r', '-n', '7', '--event', 'approve', '-b', 'LGTM'],
{ STOKE_CONFIG_FILE: cfg },
);
clearTimeout(timer);
server.close(() => resolve(res));
} catch (err) {
fail(err);
}
});
}).finally(() => clearTimeout(timer));
try {
assert.equal(result.status, 0, result.stderr);
assert.match(result.stdout, /Review submitted on !7: APPROVED/);
assert.match(result.stdout, /URL: https:\/\/forge\.test\/pulls\/7#issuecomment-42/);
} finally {
fs.unlinkSync(cfg);
}
});