GitNexus/gitnexus/test/unit/changed-coverage.test.ts
Gergő Magyar 299ebfcd6d
ci: run SonarCloud analysis on fork PRs and gate coverage in Actions (#4262)
* ci: run SonarCloud analysis on fork PRs and gate coverage in Actions

* ci: enforce app-pinned Sonar and changed-code coverage gates

* ci: classify repository sources and tests in Sonar automatic analysis

* ci: enforce HTTPS for SpotBugs and simplify coverage validation

---------

Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
2026-11-29 08:05:30 +00:00

297 lines
11 KiB
TypeScript

import { execFileSync, spawnSync } from 'node:child_process';
import {
copyFileSync,
cpSync,
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
writeFileSync,
} from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { load } from 'js-yaml';
import { afterEach, beforeEach, expect, it } from 'vitest';
const root = path.resolve(__dirname, '../../..');
const script = path.join(root, '.github/scripts/changed-coverage.cjs');
const cli = 'gitnexus/src/lib/a file.ts';
const web = 'gitnexus-web/src/lib/a file.ts';
const cliReport = 'gitnexus/coverage/lcov.info';
const webReport = 'gitnexus-web/coverage/lcov.info';
let cwd: string;
const env = Object.fromEntries(
Object.entries(process.env).filter(([name]) => !name.startsWith('GIT_')),
);
const git = (...args: string[]) => execFileSync('git', args, { cwd, env, stdio: 'pipe' });
function write(file: string, data: string) {
const dest = path.join(cwd, file);
mkdirSync(path.dirname(dest), { recursive: true });
writeFileSync(dest, data);
}
function commit(message: string) {
git('add', '--all');
git('commit', '-qm', message, '--allow-empty', '--no-gpg-sign');
}
const source = (count: number) =>
Array.from({ length: count }, (_, i) => `export const x${i} = ${i};\n`).join('');
function lcov(file: string, lines: number[], branches: string[] = []) {
return [
'TN:',
'SF:' + file.slice(file.indexOf('/') + 1),
...lines.map((hits, i) => `DA:${i + 1},${hits}`),
`LF:${lines.length}`,
...branches.map((entry) => 'BRDA:' + entry),
`BRF:${branches.length}`,
'end_of_record',
'',
].join('\n');
}
function check(cliSelected = true, webSelected = false) {
return spawnSync(process.execPath, [script, cliReport, webReport], {
cwd,
env: { ...env, CLI: String(cliSelected), WEB: String(webSelected) },
encoding: 'utf8',
});
}
beforeEach(() => {
cwd = mkdtempSync(path.join(tmpdir(), 'changed-coverage-'));
git('init', '-q', '-b', 'base');
git('config', 'user.name', 'CI');
git('config', 'user.email', 'ci@example.invalid');
git('config', 'commit.gpgsign', 'false');
commit('empty base');
});
afterEach(() => rmSync(cwd, { force: true, recursive: true }));
it('combines both package-relative paths, line hits and branch outcomes at exactly 80%', () => {
write(cli, source(10));
write(web, source(10));
commit('change production sources');
const cliHits = Array<number>(10).fill(1);
write(cliReport, lcov(cli, cliHits, ['3,7,0,1', '3,7,1,0']));
write(webReport, lcov(web, [1, 1, 1, 1, 1, 1, 1, 1, 0, 0], ['1,8,0,1', '1,8,1,-', '1,8,2,0']));
expect(check(true, true)).toMatchObject({
status: 0,
stdout: expect.stringContaining('20/25 (80.00%)'),
});
// Only branch coverage changes, so a line-only gate would falsely pass.
write(cliReport, lcov(cli, cliHits, ['3,7,0,-', '3,7,1,0']));
expect(check(true, true)).toMatchObject({
status: 1,
stdout: expect.stringContaining('19/25 (76.00%)'),
});
});
it('fails just below 80% and displays a percentage below the threshold', () => {
write(cli, source(4004));
commit('just below threshold');
write(cliReport, lcov(cli, [...Array<number>(3203).fill(1), ...Array<number>(801).fill(0)]));
expect(check()).toMatchObject({
status: 1,
stdout: expect.stringContaining('3203/4004 (79.99%)'),
});
});
it('treats signed V8 execution counters as uncovered and rejects non-numeric counts', () => {
write(cli, source(466));
commit('CLI');
// This negative BRDA count appeared in the hosted ignore-service.ts report.
const report = lcov(cli, [1, -7364], ['466,22,1,-81']);
write(cliReport, report);
expect(check()).toMatchObject({ status: 1, stdout: expect.stringContaining('1/3 (33.33%)') });
write(cliReport, report.replace('-81', 'invalid'));
expect(check()).toMatchObject({ status: 1, stderr: expect.stringContaining('Invalid BRDA') });
});
it.each([
[19, 0],
[20, 1],
])('uses %i changed physical source lines for the small-change exemption', (count, status) => {
write(cli, 'export const x = 0;\n' + '// a comment\n'.repeat(count - 1));
write('docs/guide.md', source(40));
commit('comments and code');
write(cliReport, lcov(cli, [0]));
expect(check().status).toBe(status);
});
it('excludes renamed unchanged lines, deletions, concurrent base changes and worktree edits', () => {
const dest = 'gitnexus/src/lib/renamed.ts';
write(cli, source(50));
write('gitnexus/src/deleted.ts', source(22));
commit('common ancestor');
git('switch', '-qc', 'fork');
git('mv', cli, dest);
write(dest, source(50) + source(20));
git('rm', '-q', 'gitnexus/src/deleted.ts');
commit('fork changes');
git('switch', '-q', 'base');
write('gitnexus/src/base-only.ts', source(30));
commit('base advanced');
git('merge', '-q', '--no-ff', 'fork', '-m', 'tested merge tree');
write('gitnexus/src/untracked.ts', source(20));
write(dest, source(1));
write(cliReport, lcov(dest, [...Array<number>(50).fill(0), ...Array<number>(20).fill(1)]));
expect(check()).toMatchObject({ status: 0, stdout: expect.stringContaining('20/20 (100.00%)') });
});
it('skips docs, tests, declarations, fixtures, uninstrumented packages and Vitest exclusions', () => {
for (const file of [
'docs/guide.md',
'gitnexus/test/unit/test.ts',
'gitnexus/src/a.test.ts',
'gitnexus/src/test/x.ts',
'gitnexus/src/fixtures/x.ts',
'gitnexus/src/a.d.ts',
'gitnexus/src/cli/index.ts',
'gitnexus/src/core/wiki/a.ts',
'gitnexus-web/src/main.tsx',
'gitnexus-web/src/workers/worker.ts',
'gitnexus-web/src/core/lbug/a.ts',
'gitnexus-web/src/core/tree-sitter/a.ts',
'gitnexus-web/src/core/embeddings/a.ts',
'gitnexus-shared/src/ex.ts',
])
write(file, source(20));
commit('non-coverable changes');
expect(check(false)).toMatchObject({
status: 0,
stdout: expect.stringContaining('0 changed source lines'),
});
});
it('accepts explicit LF:0 and BRF:0 for a changed type-only file', () => {
write(cli, 'export interface Options {\n' + ' // empty\n'.repeat(20) + '}\n');
commit('types');
write(cliReport, lcov(cli, []));
expect(check()).toMatchObject({
status: 0,
stdout: expect.stringContaining('22 changed source lines, 0 lines and branches'),
});
});
it('rejects missing, truncated and incomplete reports even on a small change', () => {
write(cli, source(1));
commit('one line');
expect(check()).toMatchObject({ status: 1, stderr: expect.stringContaining('lcov.info') });
write(cliReport, lcov('gitnexus/src/unrelated.ts', [1]));
expect(check()).toMatchObject({
status: 1,
stderr: expect.stringContaining('Missing LCOV record'),
});
write(cliReport, lcov(cli, [1]).replace('end_of_record', ''));
expect(check()).toMatchObject({
status: 1,
stderr: expect.stringContaining('Incomplete LCOV report'),
});
write(cliReport, lcov(cli, [1]).replace('LF:1', 'LF:10'));
expect(check()).toMatchObject({
status: 1,
stderr: expect.stringContaining('Incomplete LCOV totals'),
});
write(cliReport, lcov(cli, [1]) + lcov(cli, [0]));
expect(check()).toMatchObject({
status: 1,
stderr: expect.stringContaining('Expected a single Vitest LCOV record'),
});
});
it.skipIf(process.platform !== 'linux').each([
[cli, cliReport, true, false],
[web, webReport, false, true],
] as const)(
'stages %s in the PR artifact before a failing gate, including a partial run',
(file, reportPath, hasCli, hasWeb) => {
const contract = load(
readFileSync(path.join(root, '.github/workflows/ci-tests.yml'), 'utf8'),
) as {
jobs: Record<
string,
{
steps: {
name?: string;
id?: string;
if?: string;
run?: string;
with?: { name?: string; path?: string };
env?: Record<string, string>;
}[];
}
>;
};
const { steps } = contract.jobs['coverage-merge'];
const snapshot = steps.findIndex(
(s) => s.name === 'Preserve Vitest CLI LCOV for changed-code coverage',
);
const merge = steps.findIndex((s) => s.id === 'conformance-lcov');
const stage = steps.findIndex((s) => s.id === 'stage-lcov');
const upload = steps.findIndex((s) => s.with?.name === 'lcov');
const gate = steps.findIndex((s) => s.run?.includes('.github/scripts/changed-coverage.cjs'));
expect(stage).toBeGreaterThan(-1);
expect(steps[stage].if).toContain("github.event_name == 'pull_request'");
expect(upload).toBeGreaterThan(stage);
expect(gate).toBeGreaterThan(upload);
expect(steps[upload].with?.path).toBe('${{ runner.temp }}/lcov/');
expect(steps[snapshot].if).toContain("github.event_name == 'pull_request'");
expect(steps[snapshot].if).toContain('fromJSON(inputs.plan).run.conformance');
expect(merge).toBeGreaterThan(snapshot);
expect(stage).toBeGreaterThan(merge);
expect(steps[gate].env?.CLI_REPORT).toBe(
"${{ fromJSON(inputs.plan).run.conformance && 'vitest-lcov.info' || 'lcov.info' }}",
);
const temp = path.join(cwd, 'runner');
write(file, source(20) + '// comment\n'.repeat(25));
commit('uncovered change');
const vitest = lcov(file, Array<number>(20).fill(0));
write(reportPath, vitest);
const scripts = '.github/scripts';
mkdirSync(path.join(cwd, scripts), { recursive: true });
for (const name of ['copy-ci-reports.sh', 'changed-coverage.cjs', 'git-executable.cjs'])
copyFileSync(path.join(root, scripts, name), path.join(cwd, scripts, name));
const shell = (step: number, dir = cwd, overrides = {}) => {
const command = steps[step].run;
if (!command) throw new Error(`Missing workflow command at step ${step}`);
return spawnSync('bash', ['-ec', command], {
cwd: dir,
env: { ...env, CLI: 'true', WEB: 'true', RUNNER_TEMP: temp, ...overrides },
encoding: 'utf8',
});
};
if (hasCli) {
expect(shell(snapshot).status).toBe(0);
// c8 marks the comment lines as executed and reports differently
// numbered branches. Retain this data for download, outside the gate.
const conformance = lcov(file, Array<number>(45).fill(1), ['1,19,0,1']);
for (const provider of ['java', 'typescript'])
write(`runner/${provider}-conformance-coverage/lcov.info`, conformance);
expect(shell(merge, path.join(cwd, 'gitnexus')).status).toBe(0);
}
// Both packages are selected, but only one emitted a report. Simulate the
// runner staging and uploading surviving files before the exit-code check.
expect(shell(stage).status).toBe(0);
const artifact = path.join(cwd, 'uploaded');
cpSync(path.join(temp, 'lcov'), artifact, { recursive: true });
const gateEnv = {
CLI: String(hasCli),
WEB: String(hasWeb),
CLI_REPORT: hasCli ? 'vitest-lcov.info' : 'lcov.info',
};
expect(shell(gate, cwd, gateEnv)).toMatchObject({
status: 1,
stdout: expect.stringContaining('0/20 (0.00%)'),
});
expect(shell(gate, cwd, { ...gateEnv, CLI: 'true', WEB: 'true' })).toMatchObject({
status: 1,
stderr: expect.stringContaining('lcov.info'),
});
expect(readFileSync(path.join(artifact, reportPath), 'utf8')).toBe(
readFileSync(path.join(cwd, reportPath), 'utf8'),
);
if (hasCli) {
expect(readFileSync(path.join(artifact, 'gitnexus/coverage/vitest-lcov.info'), 'utf8')).toBe(
vitest,
);
expect(readFileSync(path.join(artifact, reportPath), 'utf8')).toContain('DA:45,1');
}
},
);