Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
name: Tests

# Runs the Vitest suite on every PR and fails only on failures the PR
# introduces: develop still carries known failures (#3472), so the head and
# introduces: main may still carry known failures (#3472), so the head and
# base are tested in parallel and compared. Once #3472 clears the baseline,
# this can gate on zero failures instead (#3479).

Expand Down Expand Up @@ -134,11 +134,19 @@ jobs:
printf '%s\n' "$dirty"
fi

- name: List files tracked at base
if: matrix.target == 'base'
# Lets the compare job tell a test file the PR adds (new) from one
# that existed at base but is missing from its report (not comparable).
run: git ls-files > base-files.txt

- name: Upload report
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: vitest-report-${{ matrix.target }}
path: jest-report.json
path: |
jest-report.json
base-files.txt
if-no-files-found: ignore
retention-days: 7

Expand Down Expand Up @@ -183,10 +191,15 @@ jobs:
# makes their test paths comparable. The default shell is
# bash -e: suspend errexit so a non-zero result still reaches the
# summary below.
base_files_args=()
if [ -s reports/vitest-report-base/base-files.txt ]; then
base_files_args=(--base-files reports/vitest-report-base/base-files.txt)
fi
set +e
node scripts/validation/compare-jest-failures.cjs \
--head reports/vitest-report-head/jest-report.json --head-root "$GITHUB_WORKSPACE" \
--base reports/vitest-report-base/jest-report.json --base-root "$GITHUB_WORKSPACE" \
"${base_files_args[@]}" \
| tee comparison.txt
status=${PIPESTATUS[0]}
set -e
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed

- **Tests CI reported pre-existing failures as new** — the "No new test failures" comparison ran Jest for the base commit, which never ran TypeScript suites, so every failing `.ts` suite on head looked new (even on docs-only PRs). Both head and base now run Vitest; the comparison script labels Vitest reports correctly and reports a failing file that existed at base but is missing from the base report as "not comparable" rather than new.
- **Reader access verification never succeeded** — the code request emailed one code but stored the hash of a different one; the stored hash now derives from the emailed code, and comparison is constant-time.
- **Reader access endpoints crashed at runtime** — restored the verification-code and recovery storage functions removed from `store.ts`, and handled the real Netlify Blobs `list()` result shape so session creation no longer throws.
- **Reader API routing** — `/api/reader/code-requests` and `/api/reader/verifications` now reach their functions; `/api/reader/chapters/{id}` routes to the session-validated chapter endpoint, and chapter content reads the `sessionToken` cookie the app actually sets.
Expand Down
87 changes: 64 additions & 23 deletions scripts/validation/compare-jest-failures.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,19 @@
*
* Supports both Jest and Vitest JSON output formats. Compares test failure
* counts between the PR head and base branch to detect if the PR introduces
* new test failures. Known failures on develop don't block the PR, only NEW
* new test failures. Known failures on main don't block the PR, only NEW
* failures introduced by the PR are reported.
*
* Usage:
* node compare-jest-failures.cjs \
* --head <head-report.json> --head-root <path> \
* --base <base-report.json> --base-root <path>
* --base <base-report.json> --base-root <path> \
* [--base-files <git-ls-files-at-base.txt>]
*
* When --base-files is given, a failing head file that is missing from the
* base report but tracked at the base commit is reported as "not comparable"
* rather than "new": base never ran it, so there is no baseline. A file the
* PR adds is not tracked at base and still counts as new.
*/

const fs = require('fs');
Expand All @@ -26,7 +32,7 @@ for (let i = 0; i < args.length; i += 2) {
}

if (!opts.head || !opts.base || !['head-root', 'base-root'].every(k => opts[k])) {
console.error('Usage: node compare-jest-failures.cjs --head <file> --head-root <path> --base <file> --base-root <path>');
console.error('Usage: node compare-jest-failures.cjs --head <file> --head-root <path> --base <file> --base-root <path> [--base-files <file>]');
process.exit(1);
}

Expand All @@ -42,31 +48,49 @@ function readReport(filePath) {
}

// Detect report format: Jest vs Vitest
//
// Vitest's JSON reporter mirrors Jest's top-level counters (including
// numFailedTests), so those cannot tell the formats apart. Jest alone emits
// numRuntimeErrorTestSuites, wasInterrupted and openHandles at the top level,
// and per-file numFailingTests in its legacy output.
function detectFormat(report) {
if (!report || !Array.isArray(report.testResults)) {
return null;
}

// Both formats have testResults array, but field names differ slightly
// Vitest uses 'assertionResults' for individual test results
// Jest uses 'numFailingTests' prominently but also 'assertionResults'

// Check first result to infer format (heuristic)
const firstResult = report.testResults[0];
if (!firstResult) return 'unknown';

// Both use assertionResults, so check other fields
if (firstResult.numFailingTests !== undefined || report.numFailedTests !== undefined) {
const jestOnlyKeys = ['numRuntimeErrorTestSuites', 'wasInterrupted', 'openHandles'];
if (jestOnlyKeys.some(key => key in report)) {
return 'jest';
}
if (report.testResults.some(result => result && result.numFailingTests !== undefined)) {
return 'jest';
}

// Vitest typically has 'duration' and other fields
if (firstResult.duration !== undefined) {
return 'vitest';
return 'vitest';
}

// List every test file in a report, normalised relative to root
function listFiles(report, root) {
if (!report || !Array.isArray(report.testResults)) {
return new Set();
}
return new Set(report.testResults.map(result => path.relative(root || '.', result.name)));
}

// Default to jest for compatibility
return 'jest';
// Read the optional list of files tracked at the base commit (one per line,
// relative to the repository root, as printed by `git ls-files`)
function readFileList(filePath) {
if (!filePath) {
return null;
}
try {
return new Set(
fs.readFileSync(filePath, 'utf8').split('\n').map(line => line.trim()).filter(Boolean),
);
} catch (error) {
console.error(`Failed to read base file list ${filePath}: ${error.message}`);
process.exit(1);
}
}

// Count failures by test file, normalized relative to root
Expand Down Expand Up @@ -130,15 +154,24 @@ const baseFormat = detectFormat(baseReport);
const headFailures = countFailures(headReport, opts['head-root']);
const baseFailures = countFailures(baseReport, opts['base-root']);

// Calculate per-file comparison: count new failures (head > base)
const newFailuresByFile = Object.entries(headFailures).reduce((acc, [file, count]) => {
const baseReportFiles = listFiles(baseReport, opts['base-root']);
const baseTrackedFiles = readFileList(opts['base-files']);

// Calculate per-file comparison: count new failures (head > base). A file
// that base never reported cannot be compared if it already existed there.
const newFailuresByFile = {};
const notComparableByFile = {};
Object.entries(headFailures).forEach(([file, count]) => {
if (!baseReportFiles.has(file) && baseTrackedFiles && baseTrackedFiles.has(file)) {
notComparableByFile[file] = count;
return;
}
const baseCount = baseFailures[file] || 0;
const newCount = Math.max(0, count - baseCount);
if (newCount > 0) {
acc[file] = { head: count, base: baseCount, new: newCount };
newFailuresByFile[file] = { head: count, base: baseCount, new: newCount };
}
return acc;
}, {});
});

const headTotal = Object.values(headFailures).reduce((a, b) => a + b, 0);
const baseTotal = Object.values(baseFailures).reduce((a, b) => a + b, 0);
Expand All @@ -148,6 +181,14 @@ console.log(`Base branch failures: ${baseTotal} (${Object.keys(baseFailures).len
console.log(`PR head failures: ${headTotal} (${Object.keys(headFailures).length} files) [${headFormat}]`);
console.log(`New failures in this PR: ${totalNewFailures}`);

const notComparable = Object.entries(notComparableByFile);
if (notComparable.length > 0) {
console.log(`\n⚠️ ${notComparable.length} failing file(s) not comparable (exist at base but missing from the base report):`);
notComparable.forEach(([file, count]) => {
console.log(` • ${file}: ${count} failure(s) on head`);
});
}

if (totalNewFailures > 0) {
console.error(`\n❌ This PR introduces ${totalNewFailures} new test failure(s):`);
Object.entries(newFailuresByFile).forEach(([file, data]) => {
Expand Down
98 changes: 97 additions & 1 deletion scripts/validation/compare-jest-failures.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,20 @@ afterEach(() => {
* and optional statuses and assertion results.
* @param {Array<Object>} baseFiles - Base suite fixtures in the same format.
* @param {boolean} [rawCounts=false] - Use numeric failure counts instead of assertion results.
* @param {Object} [options] - Extra fixture options.
* @param {Object} [options.topLevel] - Extra top-level report fields per target ({ head, base }).
* @param {Array<string>} [options.baseTracked] - Files tracked at base, passed as --base-files.
* @returns {import('node:child_process').SpawnSyncReturns<string>} CLI output and exit status.
*/
function compare(headFiles, baseFiles, rawCounts = false) {
function compare(headFiles, baseFiles, rawCounts = false, options = {}) {
const roots = {
head: path.join(fixtureRoot, 'head'),
base: path.join(fixtureRoot, 'base'),
};

Object.entries({ head: headFiles, base: baseFiles }).forEach(([target, files]) => {
const report = {
...(options.topLevel?.[target] || {}),
numFailedTests: files.reduce((total, file) => total + file.failures, 0),
testResults: files.map(file => {
const result = {
Expand All @@ -53,12 +57,20 @@ function compare(headFiles, baseFiles, rawCounts = false) {
writeFileSync(path.join(fixtureRoot, `${target}.json`), JSON.stringify(report));
});

const extraArgs = [];
if (options.baseTracked) {
const listPath = path.join(fixtureRoot, 'base-files.txt');
writeFileSync(listPath, `${options.baseTracked.join('\n')}\n`);
extraArgs.push('--base-files', listPath);
}

return spawnSync(process.execPath, [
script,
'--head', path.join(fixtureRoot, 'head.json'),
'--head-root', roots.head,
'--base', path.join(fixtureRoot, 'base.json'),
'--base-root', roots.base,
...extraArgs,
], { encoding: 'utf8' });
}

Expand Down Expand Up @@ -184,3 +196,87 @@ test('also compares reports containing per-file numeric failure counts', () => {
expect(result.status).toBe(1);
expect(result.stdout).toContain('New failures in this PR: 2');
});

describe('report format detection', () => {
const jestTopLevel = { numRuntimeErrorTestSuites: 0, wasInterrupted: false, openHandles: [] };

test('labels Vitest reports as vitest even though they carry numFailedTests', () => {
const files = [{ name: 'tests/existing.test.ts', failures: 1 }];
const result = compare(files, files);

expect(result.stdout).toMatch(/Base branch failures: .*\[vitest\]/);
expect(result.stdout).toMatch(/PR head failures: .*\[vitest\]/);
});

test('labels reports with Jest-only top-level fields as jest', () => {
const files = [{ name: 'tests/existing.test.js', failures: 1 }];
const result = compare(files, files, false, { topLevel: { base: jestTopLevel } });

expect(result.stdout).toMatch(/Base branch failures: .*\[jest\]/);
expect(result.stdout).toMatch(/PR head failures: .*\[vitest\]/);
});

test('labels legacy per-file numFailingTests reports as jest', () => {
const files = [{ name: 'tests/existing.test.js', failures: 1 }];
const result = compare(files, files, true);

expect(result.stdout).toMatch(/PR head failures: .*\[jest\]/);
});
});

describe('--base-files', () => {
test('reports a failing file that existed at base but is missing from its report as not comparable', () => {
const result = compare(
[{ name: 'tests/existing.test.ts', failures: 2 }],
[{ name: 'tests/other.test.ts', failures: 0 }],
false,
{ baseTracked: ['tests/existing.test.ts', 'tests/other.test.ts'] },
);

expect(result.status).toBe(0);
expect(result.stdout).toContain('New failures in this PR: 0');
expect(result.stdout).toContain('not comparable');
expect(result.stdout).toContain('tests/existing.test.ts: 2 failure(s) on head');
});

test('still counts a failing file added by the PR as new', () => {
const result = compare(
[{ name: 'tests/added.test.ts', failures: 1 }],
[],
false,
{ baseTracked: ['tests/existing.test.ts'] },
);

expect(result.status).toBe(1);
expect(result.stdout).toContain('New failures in this PR: 1');
expect(result.stdout).not.toContain('not comparable');
});

test('still compares a file that base reported as passing', () => {
const result = compare(
[{ name: 'tests/existing.test.ts', failures: 1 }],
[{ name: 'tests/existing.test.ts', failures: 0 }],
false,
{ baseTracked: ['tests/existing.test.ts'] },
);

expect(result.status).toBe(1);
expect(result.stdout).toContain('New failures in this PR: 1');
});

test('fails when the base file list cannot be read', () => {
const files = [{ name: 'tests/existing.test.ts', failures: 0 }];
compare(files, files);
const result = spawnSync(process.execPath, [
script,
'--head', path.join(fixtureRoot, 'head.json'),
'--head-root', path.join(fixtureRoot, 'head'),
'--base', path.join(fixtureRoot, 'base.json'),
'--base-root', path.join(fixtureRoot, 'base'),
'--base-files', path.join(fixtureRoot, 'missing.txt'),
], { encoding: 'utf8' });

expect(result.status).toBe(1);
expect(result.stderr).toContain('Failed to read base file list');
});
});
Loading