GitNexus/gitnexus/test/unit/sonar-coverage-workflow.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

538 lines
21 KiB
TypeScript

import { spawnSync } from 'node:child_process';
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { runInNewContext } from 'node:vm';
import { load } from 'js-yaml';
import { afterEach, describe, expect, it, vi } from 'vitest';
type Step = {
name?: string;
run?: string;
if?: string;
shell?: string;
env?: Record<string, string>;
with?: Record<string, string>;
'continue-on-error'?: boolean;
'timeout-minutes'?: number;
};
type Job = {
if?: string;
steps?: Step[];
needs?: string | string[];
permissions?: Record<string, string>;
env?: Record<string, string>;
with?: Record<string, string>;
};
function readWorkflow(name: string) {
const file = path.resolve(__dirname, '../../../.github/workflows', name + '.yml');
return load(readFileSync(file, 'utf8')) as {
on: {
pull_request?: { branches?: string[] };
workflow_run?: { workflows: string[]; types: string[]; branches: string[] };
};
jobs: Record<string, Job>;
};
}
function namedStep(steps: Step[], name: string) {
const step = steps.find((candidate) => candidate.name === name);
if (!step) throw new Error(`Missing workflow step: ${name}`);
return step;
}
const producer = readWorkflow('ci-tests').jobs['coverage-merge'].steps ?? [];
let temp: string;
afterEach(() => {
if (temp) rmSync(temp, { recursive: true, force: true });
});
describe('SonarQube Cloud quality gate', () => {
const ci = readWorkflow('ci');
const gate = ci.jobs['ci-status'];
const step = namedStep(gate.steps ?? [], 'Require SonarQube Cloud quality gate');
const run = {
id: 42,
app: { id: 12526 },
name: 'SonarCloud Code Analysis',
head_sha: 'pr-head-sha',
status: 'completed',
conclusion: 'success',
details_url: 'https://sonarcloud.io/dashboard?id=abhigyanpatwari_GitNexus&pullRequest=123',
};
it('checks every PR with read-only access and no checkout', () => {
expect(ci.on.pull_request).toBeNull();
expect(step.if).toBe("github.event_name == 'pull_request'");
expect(step['timeout-minutes']).toBe(45);
expect(step.with?.retries).toBeUndefined();
expect(gate.permissions).toEqual({ checks: 'read' });
expect(gate.steps?.map((entry) => entry.name)).toEqual([
'Check all jobs passed',
'Require SonarQube Cloud quality gate',
]);
expect(readWorkflow('publish').jobs.ci.permissions).not.toHaveProperty('id-token');
});
type ApiError = {
status: number;
message: string;
response?: { headers: Record<string, string> };
};
const requiredCheck = { context: run.name, integration_id: run.app.id };
const statusRule = (...checks: { context: string; integration_id?: number }[]) => ({
type: 'required_status_checks',
parameters: { required_status_checks: checks },
});
const activeRule = statusRule(requiredCheck);
async function verify(
polls: ((typeof run)[] | ApiError)[],
{
owner = 'abhigyanpatwari',
repo = 'GitNexus',
base = 'main',
defaultBranch = 'main',
rules = [[activeRule]],
}: {
owner?: string;
repo?: string;
base?: string;
defaultBranch?: string;
rules?: (object[] | ApiError)[];
} = {},
) {
let now = 0;
const delays: number[] = [];
const listForRef = vi.fn();
const listRules = vi.fn();
const paginate = vi.fn(async (route, params) => {
let result;
if (route === listForRef) {
listForRef(params);
result = polls.shift() ?? [];
} else {
expect(route).toBe('GET /repos/{owner}/{repo}/rules/branches/{branch}');
listRules(params);
result = rules.shift() ?? [];
}
if (!Array.isArray(result)) throw result;
return result;
});
const setFailed = vi.fn();
await runInNewContext('(async () => {' + step.with!.script + '})()', {
URL,
github: { paginate, rest: { checks: { listForRef } } },
context: {
repo: { owner, repo },
payload: {
repository: { default_branch: defaultBranch },
pull_request: { number: 123, head: { sha: run.head_sha }, base: { ref: base } },
},
},
core: { info: vi.fn(), setFailed },
Date: { now: () => now, parse: Date.parse },
setTimeout: (resolve: () => void, delay: number) => {
delays.push(delay);
now += delay;
resolve();
},
});
expect(paginate).toHaveBeenCalledWith(listForRef, {
owner,
repo,
ref: run.head_sha,
app_id: run.app.id,
check_name: run.name,
filter: 'all',
per_page: 100,
});
return { listForRef, listRules, setFailed, delays };
}
it('waits for the latest analysis and accepts its success', async () => {
const queued = { ...run, id: 43, status: 'queued', details_url: '' };
const { listForRef, listRules, setFailed } = await verify([
[],
[run, queued],
[{ ...run, id: 43 }],
]);
expect(listForRef).toHaveBeenCalledTimes(3);
expect(listRules).toHaveBeenCalledExactlyOnceWith({
owner: 'abhigyanpatwari',
repo: 'GitNexus',
branch: 'main',
per_page: 100,
});
expect(listRules.mock.invocationCallOrder[0]).toBeGreaterThan(
listForRef.mock.invocationCallOrder[2],
);
expect(setFailed).not.toHaveBeenCalled();
});
it.each(['failure', 'cancelled', 'skipped', 'neutral', 'timed_out'])(
'rejects a new %s result even after an older success',
async (conclusion) => {
const { setFailed, listRules } = await verify([[run, { ...run, id: 43, conclusion }]]);
expect(listRules).not.toHaveBeenCalled();
expect(setFailed).toHaveBeenCalledWith(expect.stringContaining(conclusion));
},
);
it.each([
{ app: { id: 7 } },
{ head_sha: 'merge-sha' },
{ name: 'Another check' },
{ details_url: '' },
{ details_url: run.details_url.replace('123', '456') },
{ details_url: run.details_url.replace('GitNexus', 'AnotherProject') },
{ details_url: run.details_url.replace('sonarcloud.io', 'example.com') },
{ details_url: run.details_url.replace('pullRequest=123', 'branch=feature') },
])(
'blocks when the only completed check has unrelated or missing metadata (%j)',
async (fields) => {
const { setFailed } = await verify([[{ ...run, ...fields }]]);
expect(setFailed).toHaveBeenCalledWith(
expect.stringContaining('No completed SonarQube Cloud check'),
);
},
);
it('accepts the PR result when another PR on the same commit reported later', async () => {
const otherPR = { ...run, id: 43, details_url: run.details_url.replace('123', '456') };
const { setFailed } = await verify([[run, otherPR]]);
expect(setFailed).not.toHaveBeenCalled();
});
const branchUrl = run.details_url.replace('pullRequest=123', 'branch=feature');
it('finds the PR result behind a newer completed branch analysis', async () => {
const branch = { ...run, id: 43, conclusion: 'failure', details_url: branchUrl };
const { listForRef, setFailed } = await verify([[branch, run]]);
expect(listForRef).toHaveBeenCalledTimes(1);
expect(setFailed).not.toHaveBeenCalled();
});
it.each([
{ status: 'in_progress', details_url: branchUrl },
{ details_url: branchUrl.replace('branch=feature', 'branch=') },
{ details_url: branchUrl.replace('id=abhigyanpatwari_GitNexus&', '') },
{ details_url: branchUrl + '&pullRequest=' },
{ details_url: branchUrl + '&pullRequest=123' },
{ details_url: run.details_url + '&pullRequest=456' },
])('waits when a newer check is pending or ambiguous (%j)', async (fields) => {
const { listForRef, setFailed } = await verify([
[run, { ...run, id: 43, ...fields }],
[{ ...run, id: 43, conclusion: 'failure' }],
]);
expect(listForRef).toHaveBeenCalledTimes(2);
expect(setFailed).toHaveBeenCalledWith(expect.stringContaining('failure'));
});
it.each([
[403, { 'retry-after': '90' }, 90_000],
[403, { 'x-ratelimit-remaining': '0', 'x-ratelimit-reset': '180' }, 180_000],
[429, { 'retry-after': 'Thu, 01 Jan 1970 00:03:00 GMT' }, 180_000],
[
429,
{ 'retry-after': '120', 'x-ratelimit-remaining': '20', 'x-ratelimit-reset': '900' },
120_000,
],
] as const)('honors a rate-limited %i response (%j)', async (status, headers, delay) => {
const { delays, setFailed } = await verify([
{ status, message: 'Try again later', response: { headers } },
[run],
]);
expect(delays).toEqual([delay]);
expect(setFailed).not.toHaveBeenCalled();
});
it('backs off on repeated secondary rate limits without headers', async () => {
const error = { status: 403, message: 'You have exceeded a secondary rate limit.' };
const { delays, setFailed } = await verify([error, error, [run]]);
expect(delays).toEqual([60_000, 120_000]);
expect(setFailed).not.toHaveBeenCalled();
});
it('stops at the deadline when GitHub asks for a longer wait', async () => {
const { listForRef, delays, setFailed } = await verify([
[],
{
status: 429,
message: 'Too many requests',
response: { headers: { 'retry-after': '3600' } },
},
[run],
]);
expect(listForRef).toHaveBeenCalledTimes(2);
expect(delays.reduce((sum, delay) => sum + delay, 0)).toBeLessThanOrEqual(45 * 60_000);
expect(setFailed).toHaveBeenCalled();
});
it.each([401, 403, 404])('fails immediately on a permanent %i response', async (status) => {
const error = { status, message: 'Resource not accessible by integration' };
await expect(verify([error, [run]])).rejects.toBe(error);
});
it('preserves two retries for GitHub server errors', async () => {
const error = { status: 503, message: 'Service unavailable' };
const { delays, setFailed } = await verify([error, error, [run]]);
expect(delays).toEqual([1000, 4000]);
expect(setFailed).not.toHaveBeenCalled();
await expect(verify([error, error, error, [run]])).rejects.toBe(error);
});
it.each([
['no rules', []],
['wrong rule type', [{ ...activeRule, type: 'merge_queue' }]],
['any source', [statusRule({ context: run.name })]],
['wrong app', [statusRule({ ...requiredCheck, integration_id: 7 })]],
['wrong check', [statusRule({ ...requiredCheck, context: 'CI Gate' })]],
] as const)('fails with setup instructions for %s', async (_case, rules) => {
const { setFailed } = await verify([[run]], { rules: [[...rules]] });
expect(setFailed).toHaveBeenCalledWith(
expect.stringMatching(/ruleset.*SonarCloud Code Analysis.*12526.*rerun/i),
);
});
it.each([{ owner: 'myfork' }, { repo: 'OtherRepo' }, { base: 'release' }])(
'skips native rules on an unrelated target (%j)',
async (target) => {
const { listRules, setFailed } = await verify([[run]], { ...target, rules: [[]] });
expect(listRules).not.toHaveBeenCalled();
expect(setFailed).not.toHaveBeenCalled();
},
);
it('checks effective rules on a renamed default branch and retries a limited read', async () => {
const { delays, listForRef, listRules, setFailed } = await verify([[run]], {
base: 'trunk',
defaultBranch: 'trunk',
rules: [{ status: 429, message: 'Too many requests' }, [{ type: 'deletion' }, activeRule]],
});
expect(delays).toEqual([60_000]);
expect(listForRef).toHaveBeenCalledTimes(1);
expect(listRules).toHaveBeenCalledTimes(2);
expect(listRules).toHaveBeenCalledWith(expect.objectContaining({ branch: 'trunk' }));
expect(setFailed).not.toHaveBeenCalled();
});
it('fails closed when the default branch or its rules cannot be read', async () => {
await expect(verify([[run]], { defaultBranch: '' })).rejects.toThrow('default branch');
const error = { status: 403, message: 'Resource not accessible by integration' };
await expect(verify([[run]], { rules: [error, [activeRule]] })).rejects.toBe(error);
});
it('shares the original 45-minute budget with active rule verification', async () => {
const { delays, listRules, setFailed } = await verify([[], [run]], {
rules: [
{
status: 429,
message: 'Too many requests',
response: { headers: { 'retry-after': '2680' } },
},
[activeRule],
],
});
expect(delays).toEqual([30_000]);
expect(listRules).toHaveBeenCalledTimes(1);
expect(setFailed).toHaveBeenCalled();
});
});
describe.skipIf(process.platform === 'win32')('selected CI checks', () => {
const ci = readWorkflow('ci');
const gate = namedStep(ci.jobs['ci-status'].steps ?? [], 'Check all jobs passed');
it('takes the required checks from the plan and the actual results from the jobs', () => {
const java = readWorkflow('java-static-analysis');
expect(java.on).toMatchObject({ workflow_call: null, push: { branches: ['main'] } });
expect(java.jobs.analyze.if).toBeUndefined();
expect(java.jobs.analyze.steps?.every((step) => step.if === undefined)).toBe(true);
expect(ci.jobs['java-static-analysis']).toEqual({
uses: './.github/workflows/java-static-analysis.yml',
permissions: { contents: 'read' },
});
expect(ci.jobs['ci-status'].needs).toContain('java-static-analysis');
expect(gate.env?.JAVA_ANALYSIS).toBe('${{ needs.java-static-analysis.result }}');
expect(gate.env?.PLAN_RESULT).toBe('${{ needs.plan.result }}');
expect(gate.env?.PLAN_AVAILABLE).toBe("${{ needs.plan.outputs.checks != '' }}");
expect(gate.env?.E2E).toBe('${{ needs.e2e.result }}');
expect(gate.env?.E2E_REQUIRED).toContain('.run.browser');
expect(gate.env?.QUALITY).toBe('${{ needs.quality.result }}');
for (const lane of ['quality', 'cli', 'web', 'workflows']) {
expect(gate.env?.QUALITY_REQUIRED).toContain('.run.' + lane);
}
});
it.each([
['required E2E skipped', { E2E: 'skipped', E2E_REQUIRED: 'true' }, 1],
['optional E2E skipped', { E2E: 'skipped', E2E_REQUIRED: 'false' }, 0],
['required quality skipped', { QUALITY: 'skipped', QUALITY_REQUIRED: 'true' }, 1],
['optional quality skipped', { QUALITY: 'skipped', QUALITY_REQUIRED: 'false' }, 0],
['Java static analysis skipped', { JAVA_ANALYSIS: 'skipped' }, 1],
['Java static analysis failed', { JAVA_ANALYSIS: 'failure' }, 1],
['plan failed', { PLAN_RESULT: 'failure' }, 1],
['missing plan output', { PLAN_AVAILABLE: 'false' }, 1],
] as const)('%s', (_description, env, expected) => {
const result = spawnSync('bash', ['-eo', 'pipefail', '-c', gate.run!], {
env: {
PLAN_RESULT: 'success',
PLAN_AVAILABLE: 'true',
E2E: 'success',
QUALITY: 'success',
JAVA_ANALYSIS: 'success',
TESTS: 'success',
...env,
},
encoding: 'utf8',
});
expect(result.status, result.stderr).toBe(expected);
});
it.each([
[{}, 0],
[{ RUN_CLI: 'true', TESTS: 'skipped' }, 1],
[{ RUN_CONFORMANCE: 'true', CONFORMANCE: 'failure' }, 1],
[{ RUN_CONFORMANCE: 'false', CONFORMANCE: 'skipped' }, 0],
] as const)('checks results before merging coverage (%j)', (env, expected) => {
const step = namedStep(producer, 'Require selected CLI suites');
const result = spawnSync('bash', ['-eo', 'pipefail', '-c', step.run!], {
env: {
RUN_CLI: 'true',
RUN_CONFORMANCE: 'true',
TESTS: 'success',
CONFORMANCE: 'success',
...env,
},
encoding: 'utf8',
});
expect(result.status, result.stderr).toBe(expected);
});
it.each([
[{}, 0],
[{ RUN_COVERAGE: 'true', COVERAGE: 'skipped' }, 1],
[{ RUN_EVAL: 'true', EVAL: 'failure' }, 1],
[{ RUN_ABI: 'true', ABI: 'cancelled' }, 1],
[{ RUN_ABI: 'false', ABI: 'success' }, 1],
] as const)('checks results of each selected PR suite (%j)', (env, expected) => {
const audit = readWorkflow('ci-tests').jobs['test-completeness'];
const step = namedStep(audit.steps ?? [], 'Require every selected PR suite to pass');
const result = spawnSync('bash', ['-eo', 'pipefail', '-c', step.run!], {
env: {
RUN_COVERAGE: 'false',
COVERAGE: 'skipped',
RUN_EVAL: 'false',
EVAL: 'skipped',
RUN_ABI: 'false',
ABI: 'skipped',
...env,
},
encoding: 'utf8',
});
expect(result.status, result.stderr).toBe(expected);
});
it('grants release planning access to PR and Actions evidence through both workflow calls', () => {
for (const job of [ci.jobs.plan, readWorkflow('publish').jobs.ci]) {
expect(job.permissions).toMatchObject({ 'pull-requests': 'read', actions: 'read' });
}
});
it('pins each cross-run download to the PR run the release planner verified', () => {
const audit = readWorkflow('ci-tests').jobs['test-completeness'].steps ?? [];
for (const step of [
namedStep(producer, 'Download verified PR package reports'),
namedStep(audit, 'Download verified PR pytest receipt'),
namedStep(audit, 'Download verified PR preflight receipt'),
]) {
expect(step.with?.['run-id']).toBe('${{ fromJSON(inputs.plan).source }}');
}
});
});
describe('GitHub Actions coverage reports', () => {
it('enforces package thresholds and publishes LCOV on all PRs', () => {
const step = (name: string) => namedStep(producer, name);
const merge = step('Merge coverage + enforce thresholds');
const conformance = step('Add compiler conformance to the CLI LCOV report');
const web = step('Run gitnexus-web unit tests');
const upload = step('Upload LCOV reports');
expect(merge['continue-on-error']).toBeUndefined();
expect(web['continue-on-error']).toBeUndefined();
for (const name of [
'Download Java conformance LCOV',
'Download TypeScript conformance LCOV',
'Add compiler conformance to the CLI LCOV report',
'Install gitnexus-web dependencies',
'Run gitnexus-web unit tests',
]) {
expect(step(name).if).toContain('!cancelled()');
}
for (const provider of ['Java', 'TypeScript']) {
const download = step('Download ' + provider + ' conformance LCOV');
expect(download.if).toContain('fromJSON(inputs.plan).run.conformance');
expect(download.if).toContain("needs.compiler-conformance.result == 'success'");
}
expect(producer.indexOf(conformance)).toBeGreaterThan(producer.indexOf(merge));
expect(upload.if).toBe("${{ !cancelled() && steps.stage-lcov.outcome == 'success' }}");
expect(upload['continue-on-error']).toBeUndefined();
expect(upload.with).toMatchObject({ name: 'lcov', path: '${{ runner.temp }}/lcov/' });
const stage = step('Stage LCOV reports');
expect(stage.if).toContain('fromJSON(inputs.plan).coverage');
expect(stage.if).toContain("github.event_name == 'pull_request'");
const evidence = step('Stage selected package evidence');
expect(stage.run?.trimEnd()).toMatch(/copy-ci-reports\.sh .* lcov$/);
expect(evidence.run).toMatch(/copy-ci-reports\.sh .* evidence$/);
for (const source of [stage, evidence]) {
expect(source.env).toMatchObject({
CLI: "${{ contains(fromJSON(inputs.plan).packages, 'cli') }}",
WEB: "${{ contains(fromJSON(inputs.plan).packages, 'web') }}",
});
}
expect(producer.indexOf(upload)).toBeGreaterThan(
producer.indexOf(step('Run docker-server integration tests')),
);
});
it.skipIf(process.platform === 'win32')(
'appends Java and TypeScript hits and requires the CLI report',
() => {
temp = mkdtempSync(path.join(tmpdir(), 'sonar-conformance-coverage-'));
const coverage = path.join(temp, 'coverage');
const java = path.join(temp, 'java-conformance-coverage');
mkdirSync(coverage);
mkdirSync(java);
const typescript = path.join(temp, 'typescript-conformance-coverage');
mkdirSync(typescript);
const source = 'SF:src/index.ts\nDA:1,0\nend_of_record\n';
const javaSource = 'SF:src/ingestion.ts\nDA:2,1\nend_of_record\n';
writeFileSync(path.join(java, 'lcov.info'), javaSource);
const tsSource = 'SF:src/typescript.ts\nDA:3,1\nend_of_record\n';
writeFileSync(path.join(typescript, 'lcov.info'), tsSource);
const script = namedStep(producer, 'Add compiler conformance to the CLI LCOV report').run;
if (!script) throw new Error('Missing compiler LCOV merge step');
const combine = () =>
spawnSync('bash', ['-e', '-c', script], {
cwd: temp,
env: { ...process.env, RUNNER_TEMP: temp },
});
expect(combine().status).toBe(1);
writeFileSync(path.join(coverage, 'lcov.info'), source);
expect(combine().status).toBe(0);
expect(readFileSync(path.join(coverage, 'lcov.info'), 'utf8')).toBe(
source + javaSource + tsSource,
);
},
);
it('only saves shard timings for a manual run on main', () => {
expect(readWorkflow('ci-tests').jobs['save-shard-timings'].if).toBe(
"github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main'",
);
});
});