diff --git a/.github/scripts/mutation-reports.mjs b/.github/scripts/mutation-reports.mjs index d062f08..8824e42 100644 --- a/.github/scripts/mutation-reports.mjs +++ b/.github/scripts/mutation-reports.mjs @@ -29,28 +29,31 @@ const atOrAfter = (a, b) => a.line > b.line || (a.line === b.line && a.column >= // Report columns are one-based; Stryker reads range columns as zero-based. const inRange = ({ start, end }, range) => - atOrAfter({ line: start.line, column: start.column - 1 }, range.start) - && atOrAfter(range.end, { line: end.line, column: end.column - 1 }); + atOrAfter({ line: start.line, column: start.column - 1 }, range.start) && + atOrAfter(range.end, { line: end.line, column: end.column - 1 }); // The plans escape magic characters as one-character classes for Stryker. -export const unescape = (file) => file.replace(/^\.\/!/, '!').replace(/\[([?*()[\]{}])\]/g, '$1'); +export const unescapePath = file => file.replace(/^\.\/!/, '!').replace(/\[([?*()[\]{}])\]/g, '$1'); -export const escape = (file) => file.replace(/^!/, './!').replace(/[?*()[\]{}]/g, '[$&]'); +export const escapePath = file => file.replace(/^!/, './!').replace(/[?*()[\]{}]/g, '[$&]'); // A --mutate list as each file mapped to true (the whole file) or its line ranges. export function parseScope(mutate) { const scope = new Map(); for (const entry of mutate.split(',').filter(Boolean)) { const range = RANGE.exec(entry); - const file = normalise(unescape(range ? range[1] : entry)); + const file = normalise(unescapePath(range ? range[1] : entry)); const current = scope.get(file); if (!range) { scope.set(file, true); } else if (current !== true) { - scope.set(file, [...(current ?? []), { - start: { line: Number(range[3]), column: Number(range[4] ?? 0) }, - end: { line: Number(range[5]), column: Number(range[6] ?? Infinity) }, - }]); + scope.set(file, [ + ...(current ?? []), + { + start: { line: Number(range[3]), column: Number(range[4] ?? 0) }, + end: { line: Number(range[5]), column: Number(range[6] ?? Infinity) }, + }, + ]); } } return scope; @@ -58,10 +61,10 @@ export function parseScope(mutate) { export const inScope = (scope, file, { location }) => { const ranges = scope?.get(normalise(file)); - return ranges === true || (Array.isArray(ranges) && ranges.some((range) => inRange(location, range))); + return ranges === true || (Array.isArray(ranges) && ranges.some(range => inRange(location, range))); }; -const readJson = (file) => { +const readJson = file => { try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { @@ -69,11 +72,14 @@ const readJson = (file) => { } }; -const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value); +const isObject = value => typeof value === 'object' && value !== null && !Array.isArray(value); -const isReport = (report) => isObject(report) && isObject(report.files) - && Object.values(report.files).every((result) => isObject(result) - && (result.mutants === undefined || Array.isArray(result.mutants))); +const isReport = report => + isObject(report) && + isObject(report.files) && + Object.values(report.files).every( + result => isObject(result) && (result.mutants === undefined || Array.isArray(result.mutants)), + ); // The report only when Stryker wrote it after the marker, so a restored or truncated one never counts. export function readFresh(reportPath, markerPath) { @@ -110,26 +116,28 @@ export function collectShards(dir, prefix, shards, recordName) { let names = []; try { names = fs.readdirSync(dir); - } catch {} + } catch { + // An unreadable or missing folder holds no artifacts, so every shard is missing. + } const locate = (base, name) => - [path.join(base, 'reports', name), path.join(base, name)].find((file) => fs.existsSync(file)) ?? null; + [path.join(base, 'reports', name), path.join(base, name)].find(file => fs.existsSync(file)) ?? null; const entry = (shard, base) => ({ shard, - locate: (name) => locate(base, name), - read: (name) => { + locate: name => locate(base, name), + read: name => { const file = locate(base, name); return file && readJson(file); }, }); const found = new Map(); - const isDir = (name) => { + const isDir = name => { try { return fs.statSync(path.join(dir, name)).isDirectory(); } catch { return false; } }; - if (names.some((name) => name.startsWith(prefix) && isDir(name))) { + if (names.some(name => name.startsWith(prefix) && isDir(name))) { for (const shard of shards) { const base = path.join(dir, `${prefix}${shard}`); if (fs.existsSync(base)) { @@ -142,10 +150,13 @@ export function collectShards(dir, prefix, shards, recordName) { const shard = named === undefined ? (shards.length === 1 ? shards[0] : null) : named; found.set(shard, entry(shard, dir)); } - const missing = shards.filter((shard) => !found.has(shard)); + const missing = shards.filter(shard => !found.has(shard)); return { found: [...found.values()], missing }; } +// The first copy of a mutant stands until a copy its shard owns replaces one it does not. +const prefer = (current, copy) => (!current || (!current.owned && copy.owned) ? copy : current); + // Unions reports by mutant and test key. A shard's own scope wins over carried copies, and a carried copy its // owner no longer reports is dropped as a mutant the code no longer has. export function mergeReports(entries, scopes) { @@ -180,33 +191,33 @@ export function mergeReports(entries, scopes) { } for (const mutant of result.mutants ?? []) { const key = mutantKey(normalise(file), mutant); - const current = entry.mutants.get(key); - const owned = owns(shard, file, mutant); - if (!current || (!current.owned && owned)) { - entry.mutants.set(key, { mutant, owned, ids: idMaps[index] }); - } + const copy = { mutant, owned: owns(shard, file, mutant), ids: idMaps[index] }; + entry.mutants.set(key, prefer(entry.mutants.get(key), copy)); } chosen.set(normalise(file), entry); } }); - const owners = entries.map(({ shard }) => shard).filter((shard) => shard !== null); + const owners = entries.map(({ shard }) => shard).filter(shard => shard !== null); let stale = 0; for (const [file, entry] of chosen) { for (const [key, { mutant, owned }] of entry.mutants) { - if (!owned && owners.some((shard) => owns(shard, file, mutant))) { + if (!owned && owners.some(shard => owns(shard, file, mutant))) { entry.mutants.delete(key); stale++; } } - if (entry.mutants.size === 0 && !entry.owned && owners.some((shard) => - scopes.get(shard)?.get(normalise(file)) === true)) { + if ( + entry.mutants.size === 0 && + !entry.owned && + owners.some(shard => scopes.get(shard)?.get(normalise(file)) === true) + ) { chosen.delete(file); } } let count = 0; - const remap = (ids, list) => list?.map((id) => ids.get(id)).filter((id) => id !== undefined); + const remap = (ids, list) => list?.map(id => ids.get(id)).filter(id => id !== undefined); const files = {}; for (const [file, { result, mutants }] of chosen) { files[file] = { @@ -255,7 +266,9 @@ export function undetectedLines(report) { for (const [file, result] of Object.entries(report.files)) { for (const mutant of result.mutants ?? []) { if (['Survived', 'NoCoverage'].includes(mutant.status)) { - const replacement = String(mutant.replacement ?? '').replace(/\s+/g, ' ').slice(0, 80); + const replacement = String(mutant.replacement ?? '') + .replace(/\s+/g, ' ') + .slice(0, 80); const { line, column } = mutant.location.start; const { status, mutatorName } = mutant; lines.push(`${normalise(file)}:${line}:${column} ${status} ${mutatorName} ${replacement}`); @@ -308,9 +321,10 @@ export function testCosts(report) { // test, so each counts as the average. export function mutantWeight(mutant, costs = new Map()) { const covering = mutant.coveredBy ?? []; - const each = mutant.static || covering.length === 0 - ? 1 - : covering.reduce((sum, id) => sum + (costs.get(id) ?? 1), 0) / covering.length; + const each = + mutant.static || covering.length === 0 + ? 1 + : covering.reduce((sum, id) => sum + (costs.get(id) ?? 1), 0) / covering.length; return 1 + (mutant.testsCompleted ?? covering.length) * each; } @@ -322,17 +336,15 @@ export function measureSweep(report, shards) { const lines = {}; for (const { scope, seconds } of shards) { const time = Number.isFinite(seconds) && seconds > 0 ? seconds : 0; - const weighed = []; - for (const [file, result] of Object.entries(report.files)) { - for (const mutant of result.mutants ?? []) { - if (inScope(scope, file, mutant)) { - weighed.push({ file: normalise(file), mutant, weight: mutantWeight(mutant, costs) }); - } - } - } + const weighed = Object.entries(report.files).flatMap(([file, result]) => + (result.mutants ?? []) + .filter(mutant => inScope(scope, file, mutant)) + .map(mutant => ({ file: normalise(file), mutant, weight: mutantWeight(mutant, costs) })), + ); const total = weighed.reduce((sum, { weight }) => sum + weight, 0); + const unweighed = total > 0 ? 0 : time / scope.size; for (const file of scope.keys()) { - files[file] = (files[file] ?? 0) + (total > 0 ? 0 : time / scope.size); + files[file] = (files[file] ?? 0) + unweighed; } for (const { file, mutant, weight } of total > 0 ? weighed : []) { const share = (weight / total) * time; @@ -343,13 +355,18 @@ export function measureSweep(report, shards) { lines[file].set(line, [count + 1, sum + share]); } } - const listed = Object.fromEntries(Object.entries(lines).map(([file, byLine]) => [file, [...byLine] - .sort(([a], [b]) => a - b) - .map(([line, [count, sum]]) => [line, count, Math.round(sum * 1000) / 1000])])); + const listed = Object.fromEntries( + Object.entries(lines).map(([file, byLine]) => [ + file, + [...byLine] + .sort(([a], [b]) => a - b) + .map(([line, [count, sum]]) => [line, count, Math.round(sum * 1000) / 1000]), + ]), + ); return { files, lines: listed }; } -const isSeconds = (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0; +const isSeconds = value => typeof value === 'number' && Number.isFinite(value) && value >= 0; // Estimated seconds for each scope entry ({ path, range, start, end }) from the last full sweep, or null when // there is no usable sweep. A measured file costs what it took; a range costs the larger of what its lines took @@ -371,8 +388,11 @@ export function estimateScope(entries, history, lineCount) { } const recorded = (file, start, end) => { const lines = isObject(history.lines) && Array.isArray(history.lines[file]) ? history.lines[file] : []; - return lines.reduce((sum, line) => (Array.isArray(line) && line[0] >= start && line[0] <= end - && isSeconds(line[2]) ? sum + line[2] : sum), 0); + return lines.reduce( + (sum, line) => + Array.isArray(line) && line[0] >= start && line[0] <= end && isSeconds(line[2]) ? sum + line[2] : sum, + 0, + ); }; const costs = entries.map(({ path: file, range, start, end }) => { const count = lineCount(file) || 1; @@ -388,17 +408,22 @@ export function estimateScope(entries, history, lineCount) { return costs.every(Number.isFinite) && Number.isFinite(costs.reduce((sum, cost) => sum + cost, 0)) ? costs : null; } -const disjoint = (entries) => entries.every(({ range }) => range) && [...entries] - .sort((a, b) => a.start - b.start) - .every((entry, index, sorted) => index === 0 || entry.start > sorted[index - 1].end); +const disjoint = entries => + entries.every(({ range }) => range) && + [...entries] + .sort((a, b) => a.start - b.start) + .every((entry, index, sorted) => index === 0 || entry.start > sorted[index - 1].end); // Packs units ({ key, weight }), heaviest first, onto the least loaded of `count` shards. export function pack(units, count) { const sorted = [...units].sort((a, b) => b.weight - a.weight || compare(a.key, b.key)); const bins = Array.from({ length: Math.min(count, sorted.length) }, () => ({ weight: 0, units: [] })); for (const unit of sorted) { - const bin = bins.reduce((least, other) => (other.weight < least.weight - || (other.weight === least.weight && other.units.length < least.units.length) ? other : least)); + const bin = bins.reduce((least, other) => + other.weight < least.weight || (other.weight === least.weight && other.units.length < least.units.length) + ? other + : least, + ); bin.weight += unit.weight; bin.units.push(unit); } @@ -413,57 +438,58 @@ export function planScope(entries, weights, count) { entries.forEach((entry, index) => { byPath.set(entry.path, [...(byPath.get(entry.path) ?? []), { entry, weight: weights[index] }]); }); - const weigh = (items) => items.reduce((sum, { weight }) => sum + weight, 0); + const weigh = items => items.reduce((sum, { weight }) => sum + weight, 0); const total = weigh([...byPath.values()].flat()); - const units = [...byPath.keys()].sort(compare).flatMap((file) => { + const units = [...byPath.keys()].sort(compare).flatMap(file => { const items = byPath.get(file); return weigh(items) > total / count && items.length > 1 && disjoint(items.map(({ entry }) => entry)) ? items.map(({ entry, weight }) => ({ key: entry.text, weight, entries: [entry] })) : [{ key: file, weight: weigh(items), entries: items.map(({ entry }) => entry) }]; }); - return pack(units, count).map((bin) => ({ + return pack(units, count).map(bin => ({ weight: bin.weight, - entries: bin.units.flatMap((unit) => unit.entries) - .sort((a, b) => compare(a.path, b.path) || a.start - b.start), + entries: bin.units.flatMap(unit => unit.entries).sort((a, b) => compare(a.path, b.path) || a.start - b.start), })); } // Stryker's `mutate` patterns as the files on disk they select, in order, as Stryker reads them: a later `!` // pattern drops files, and a line range keeps its whole file, since the full sweep never splits one. export function expandMutate(patterns, cwd = process.cwd()) { - const skip = (entry) => /(^|[\\/])(node_modules|\.git)$/.test(typeof entry === 'string' ? entry : entry.name); + const skip = entry => /(^|[\\/])(node_modules|\.git)$/.test(typeof entry === 'string' ? entry : entry.name); + const isFile = name => { + try { + return fs.statSync(path.join(cwd, name)).isFile(); + } catch { + return false; + } + }; const selected = new Set(); for (const raw of patterns) { const text = String(raw).trim(); - if (text === '') { - continue; - } const negated = text.startsWith('!'); const body = negated ? text.slice(1) : text; const pattern = RANGE.exec(body)?.[1] ?? body; if (negated) { - for (const file of selected) { - if (path.matchesGlob(file, normalise(pattern, cwd))) { - selected.delete(file); - } + const glob = normalise(pattern, cwd); + for (const file of [...selected].filter(name => path.matchesGlob(name, glob))) { + selected.delete(file); + } + } else if (text !== '') { + const files = fs.globSync(pattern, { cwd, exclude: skip }).map(file => normalise(file, cwd)); + for (const file of files.filter(isFile)) { + selected.add(file); } - continue; - } - for (const file of fs.globSync(pattern, { cwd, exclude: skip })) { - const name = normalise(file, cwd); - try { - if (fs.statSync(path.join(cwd, name)).isFile()) { - selected.add(name); - } - } catch {} } } return [...selected].sort(); } // Packs whole files, heaviest first, onto the least loaded of `count` shards. -export const packFiles = (weights, count) => pack([...weights].map(([key, weight]) => ({ key, weight })), count) - .map((bin) => ({ weight: bin.weight, files: bin.units.map(({ key }) => key).sort(compare) })); +export const packFiles = (weights, count) => + pack( + [...weights].map(([key, weight]) => ({ key, weight })), + count, + ).map(bin => ({ weight: bin.weight, files: bin.units.map(({ key }) => key).sort(compare) })); if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) { const [command, ...args] = process.argv.slice(2); diff --git a/.github/scripts/mutation-reports.test.mjs b/.github/scripts/mutation-reports.test.mjs index 0efb330..e7b406a 100644 --- a/.github/scripts/mutation-reports.test.mjs +++ b/.github/scripts/mutation-reports.test.mjs @@ -6,7 +6,7 @@ import { describe, it } from 'node:test'; import { breaks, collectShards, - escape, + escapePath, estimateScope, expandMutate, inScope, @@ -27,15 +27,24 @@ const write = (file, content) => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, typeof content === 'string' ? content : JSON.stringify(content)); }; -const at = (line, column = 1, endLine = line, endColumn = column + 4) => - ({ start: { line, column }, end: { line: endLine, column: endColumn } }); -const mutant = (line, status, extra = {}) => - ({ id: String(line), mutatorName: 'Test', replacement: `r${line}`, location: at(line), status, ...extra }); +const at = (line, column = 1, endLine = line, endColumn = column + 4) => ({ + start: { line, column }, + end: { line: endLine, column: endColumn }, +}); +const mutant = (line, status, extra = {}) => ({ + id: String(line), + mutatorName: 'Test', + replacement: `r${line}`, + location: at(line), + status, + ...extra, +}); const report = (files, testFiles) => ({ schemaVersion: '2', thresholds: { high: 80, low: 60, break: 50 }, - files: Object.fromEntries(Object.entries(files) - .map(([file, mutants]) => [file, { language: 'typescript', source: '', mutants }])), + files: Object.fromEntries( + Object.entries(files).map(([file, mutants]) => [file, { language: 'typescript', source: '', mutants }]), + ), ...(testFiles ? { testFiles } : {}), }); @@ -46,8 +55,9 @@ describe('readFresh', () => { write(path.join(dir, 'report.json'), report({ 'a.ts': [] })); const past = new Date(Date.now() - 60_000); fs.utimesSync(path.join(dir, 'marker'), past, past); - assert.deepEqual(Object.keys(readFresh(path.join(dir, 'report.json'), path.join(dir, 'marker')).files), - ['a.ts']); + assert.deepEqual(Object.keys(readFresh(path.join(dir, 'report.json'), path.join(dir, 'marker')).files), [ + 'a.ts', + ]); }); it('rejects a report older than the marker, a broken one and a missing one', () => { @@ -72,7 +82,7 @@ describe('readFresh', () => { describe('parseScope', () => { it('keeps whole files and ranges, and undoes the plan escaping', () => { - const scope = parseScope(`${escape('src/[id].ts')},src/b.ts:10-20,src/b.ts:30:2-31`); + const scope = parseScope(`${escapePath('src/[id].ts')},src/b.ts:10-20,src/b.ts:30:2-31`); assert.equal(scope.get('src/[id].ts'), true); assert.equal(scope.get('src/b.ts').length, 2); assert.ok(inScope(scope, 'src/b.ts', mutant(15))); @@ -84,10 +94,13 @@ describe('parseScope', () => { describe('reportProblems', () => { it('names files outside the scope and untested mutants', () => { - const problems = reportProblems(report({ - 'a.ts': [mutant(1, 'Killed'), mutant(2, 'Pending'), mutant(3, undefined)], - 'b.ts': [mutant(1, 'Survived')], - }), parseScope('a.ts')); + const problems = reportProblems( + report({ + 'a.ts': [mutant(1, 'Killed'), mutant(2, 'Pending'), mutant(3, undefined)], + 'b.ts': [mutant(1, 'Survived')], + }), + parseScope('a.ts'), + ); assert.deepEqual(problems, ['has 2 untested mutant(s) in a.ts', 'reports b.ts, which is outside its scope']); }); }); @@ -98,7 +111,10 @@ describe('collectShards', () => { write(path.join(dir, 'shard-1', 'stryker.json'), report({})); write(path.join(dir, 'shard-3', 'reports', 'stryker.json'), report({})); const { found, missing } = collectShards(dir, 'shard-', [1, 2, 3]); - assert.deepEqual(found.map(({ shard }) => shard), [1, 3]); + assert.deepEqual( + found.map(({ shard }) => shard), + [1, 3], + ); assert.deepEqual(missing, [2]); assert.ok(found[1].read('stryker.json').files); assert.equal(found[0].read('absent.json'), null); @@ -108,7 +124,10 @@ describe('collectShards', () => { const dir = temp(); write(path.join(dir, 'record.json'), { shard: 2 }); const { found, missing } = collectShards(dir, 'shard-', [1, 2], 'record.json'); - assert.deepEqual(found.map(({ shard }) => shard), [2]); + assert.deepEqual( + found.map(({ shard }) => shard), + [2], + ); assert.deepEqual(missing, [1]); }); @@ -116,7 +135,10 @@ describe('collectShards', () => { const dir = temp(); write(path.join(dir, 'shard-record.json'), { shard: 2 }); const { found, missing } = collectShards(dir, 'shard-', [1], 'shard-record.json'); - assert.deepEqual(found.map(({ shard }) => shard), [2]); + assert.deepEqual( + found.map(({ shard }) => shard), + [2], + ); assert.deepEqual(missing, [1]); }); @@ -126,20 +148,31 @@ describe('collectShards', () => { }); describe('mergeReports', () => { - const testFiles = (name) => ({ [name]: { tests: [{ id: '0', name: `${name} test`, location: at(1).start }] } }); + const testFiles = name => ({ [name]: { tests: [{ id: '0', name: `${name} test`, location: at(1).start }] } }); it('unions disjoint shards and rebuilds test ids', () => { - const scopes = new Map([[1, parseScope('a.ts')], [2, parseScope('b.ts')]]); - const { report: merged, files, mutants, stale } = mergeReports([ - { - shard: 1, - report: report({ 'a.ts': [mutant(1, 'Killed', { killedBy: ['0'] })] }, testFiles('a.test.ts')), - }, - { - shard: 2, - report: report({ 'b.ts': [mutant(1, 'Survived', { coveredBy: ['0'] })] }, testFiles('b.test.ts')), - }, - ], scopes); + const scopes = new Map([ + [1, parseScope('a.ts')], + [2, parseScope('b.ts')], + ]); + const { + report: merged, + files, + mutants, + stale, + } = mergeReports( + [ + { + shard: 1, + report: report({ 'a.ts': [mutant(1, 'Killed', { killedBy: ['0'] })] }, testFiles('a.test.ts')), + }, + { + shard: 2, + report: report({ 'b.ts': [mutant(1, 'Survived', { coveredBy: ['0'] })] }, testFiles('b.test.ts')), + }, + ], + scopes, + ); assert.deepEqual([files, mutants, stale], [2, 2, 0]); assert.deepEqual(merged.files['a.ts'].mutants[0].killedBy, ['0']); assert.deepEqual(merged.files['b.ts'].mutants[0].coveredBy, ['1']); @@ -147,21 +180,33 @@ describe('mergeReports', () => { }); it('prefers the owner and drops a carried copy its owner no longer reports', () => { - const scopes = new Map([[1, parseScope('a.ts')], [2, parseScope('b.ts')]]); - const { report: merged, stale } = mergeReports([ - { shard: 1, report: report({ 'a.ts': [mutant(1, 'Killed')], 'b.ts': [mutant(9, 'Killed')] }) }, - { shard: 2, report: report({ 'b.ts': [mutant(2, 'Survived')] }) }, - ], scopes); + const scopes = new Map([ + [1, parseScope('a.ts')], + [2, parseScope('b.ts')], + ]); + const { report: merged, stale } = mergeReports( + [ + { shard: 1, report: report({ 'a.ts': [mutant(1, 'Killed')], 'b.ts': [mutant(9, 'Killed')] }) }, + { shard: 2, report: report({ 'b.ts': [mutant(2, 'Survived')] }) }, + ], + scopes, + ); assert.equal(stale, 1); - assert.deepEqual(merged.files['b.ts'].mutants.map(({ status }) => status), ['Survived']); + assert.deepEqual( + merged.files['b.ts'].mutants.map(({ status }) => status), + ['Survived'], + ); }); it('treats spellings of one path as one file', () => { const scopes = new Map([[1, parseScope('a.ts')]]); - const { files, mutants } = mergeReports([ - { shard: null, report: report({ 'a.ts': [mutant(1, 'Killed'), mutant(2, 'Survived')] }) }, - { shard: 1, report: report({ './a.ts': [mutant(1, 'Killed'), mutant(2, 'Survived')] }) }, - ], scopes); + const { files, mutants } = mergeReports( + [ + { shard: null, report: report({ 'a.ts': [mutant(1, 'Killed'), mutant(2, 'Survived')] }) }, + { shard: 1, report: report({ './a.ts': [mutant(1, 'Killed'), mutant(2, 'Survived')] }) }, + ], + scopes, + ); assert.deepEqual([files, mutants], [1, 2]); }); }); @@ -173,9 +218,14 @@ describe('scoreReport', () => { const core = path.join(dir, 'node_modules', '@stryker-mutator', 'core'); write(path.join(core, 'package.json'), { name: '@stryker-mutator/core', type: 'module' }); const metrics = path.join(core, 'node_modules', 'mutation-testing-metrics'); - write(path.join(metrics, 'package.json'), - { name: 'mutation-testing-metrics', type: 'module', main: 'index.js' }); - write(path.join(metrics, 'index.js'), `export const calculateMutationTestMetrics = (report) => { + write(path.join(metrics, 'package.json'), { + name: 'mutation-testing-metrics', + type: 'module', + main: 'index.js', + }); + write( + path.join(metrics, 'index.js'), + `export const calculateMutationTestMetrics = (report) => { const all = Object.values(report.files).flatMap((file) => file.mutants); const count = (...statuses) => all.filter((m) => statuses.includes(m.status)).length; const detected = count('Killed', 'Timeout'); @@ -184,10 +234,14 @@ describe('scoreReport', () => { mutationScore: (detected / (detected + undetected)) * 100, totalDetected: detected, timeout: count('Timeout'), totalUndetected: undetected, totalValid: detected + undetected, } } }; - };`); - const result = await scoreReport(report({ - 'a.ts': [mutant(1, 'Killed'), mutant(2, 'Timeout'), mutant(3, 'Survived'), mutant(4, 'Ignored')], - }), dir); + };`, + ); + const result = await scoreReport( + report({ + 'a.ts': [mutant(1, 'Killed'), mutant(2, 'Timeout'), mutant(3, 'Survived'), mutant(4, 'Ignored')], + }), + dir, + ); assert.deepEqual(result, { score: (2 / 3) * 100, detected: 2, timedOut: 1, undetected: 1, counted: 3 }); }); }); @@ -207,8 +261,11 @@ describe('expandMutate', () => { for (const file of ['lib/a.ts', 'lib/a.test.ts', 'lib/deep/b.ts', 'node_modules/x/lib/c.ts', 'scripts/d.ts']) { write(path.join(dir, file), 'x'); } - assert.deepEqual(expandMutate(['lib/**/*.ts', '!**/*.test.ts', 'scripts/d.ts:1-2', '', 'none/*.ts'], dir), - ['lib/a.ts', 'lib/deep/b.ts', 'scripts/d.ts']); + assert.deepEqual(expandMutate(['lib/**/*.ts', '!**/*.test.ts', 'scripts/d.ts:1-2', '', 'none/*.ts'], dir), [ + 'lib/a.ts', + 'lib/deep/b.ts', + 'scripts/d.ts', + ]); assert.deepEqual(expandMutate(['**/c.ts'], dir), []); assert.deepEqual(expandMutate(['lib/a.ts', '!./lib/a.ts'], dir), []); }); @@ -216,11 +273,35 @@ describe('expandMutate', () => { describe('packFiles', () => { it('places the heaviest files first on the least loaded shard', () => { - const bins = packFiles(new Map([['a', 5], ['b', 4], ['c', 3], ['d', 3], ['e', 1]]), 2); - assert.deepEqual(bins.map(({ weight, files }) => [weight, files]), [[8, ['a', 'd']], [8, ['b', 'c', 'e']]]); + const bins = packFiles( + new Map([ + ['a', 5], + ['b', 4], + ['c', 3], + ['d', 3], + ['e', 1], + ]), + 2, + ); + assert.deepEqual( + bins.map(({ weight, files }) => [weight, files]), + [ + [8, ['a', 'd']], + [8, ['b', 'c', 'e']], + ], + ); assert.equal(packFiles(new Map([['a', 1]]), 4).length, 1); - assert.deepEqual(packFiles(new Map([['a', 0], ['b', 0], ['c', 0]]), 3).map(({ files }) => files), - [['a'], ['b'], ['c']]); + assert.deepEqual( + packFiles( + new Map([ + ['a', 0], + ['b', 0], + ['c', 0], + ]), + 3, + ).map(({ files }) => files), + [['a'], ['b'], ['c']], + ); }); }); @@ -228,7 +309,7 @@ describe('testCosts and mutantWeight', () => { it('weighs a mutant by how much of the code its tests cover', () => { const merged = report({ 'a.ts': [mutant(1, 'Killed', { coveredBy: ['wide'], testsCompleted: 1 })], - 'b.ts': [1, 2, 3, 4].map((line) => mutant(line, 'Killed', { coveredBy: ['wide', 'narrow'] })), + 'b.ts': [1, 2, 3, 4].map(line => mutant(line, 'Killed', { coveredBy: ['wide', 'narrow'] })), }); const costs = testCosts(merged); assert.deepEqual([costs.get('wide'), costs.get('narrow')], [5 / 4.5, 4 / 4.5]); @@ -238,8 +319,10 @@ describe('testCosts and mutantWeight', () => { it('counts each test of a static mutant as the average, and falls back to the test count', () => { const costs = new Map([['wide', 4]]); - assert.equal(mutantWeight(mutant(1, 'Killed', { static: true, coveredBy: ['wide'], testsCompleted: 9 }), - costs), 10); + assert.equal( + mutantWeight(mutant(1, 'Killed', { static: true, coveredBy: ['wide'], testsCompleted: 9 }), costs), + 10, + ); assert.equal(mutantWeight(mutant(1, 'Survived', { testsCompleted: 3 })), 4); assert.equal(mutantWeight(mutant(1, 'NoCoverage')), 1); }); @@ -270,14 +353,20 @@ describe('measureSweep', () => { { scope: parseScope('a.ts:2-30'), seconds: 30 }, ]); assert.deepEqual(files, { 'a.ts': 40, 'b.ts': 10 }); - assert.deepEqual(lines, { 'a.ts': [[1, 1, 10], [20, 1, 30]], 'b.ts': [[1, 1, 10]] }); + assert.deepEqual(lines, { + 'a.ts': [ + [1, 1, 10], + [20, 1, 30], + ], + 'b.ts': [[1, 1, 10]], + }); }); it('gives a file covered by a wide test more of the shard than one covered by many narrow tests', () => { const narrow = Array.from({ length: 8 }, (_, index) => `n${index}`); const merged = report({ - 'app.ts': [1, 2].map((line) => mutant(line, 'Killed', { coveredBy: ['app'], testsCompleted: 1 })), - 'unit.ts': [1, 2].map((line) => mutant(line, 'Killed', { coveredBy: narrow, testsCompleted: 8 })), + 'app.ts': [1, 2].map(line => mutant(line, 'Killed', { coveredBy: ['app'], testsCompleted: 1 })), + 'unit.ts': [1, 2].map(line => mutant(line, 'Killed', { coveredBy: narrow, testsCompleted: 8 })), 'rest.ts': Array.from({ length: 40 }, (_, index) => mutant(index + 1, 'Killed', { coveredBy: ['app'] })), }); const { files } = measureSweep(merged, [{ scope: parseScope('app.ts,unit.ts'), seconds: 100 }]); @@ -294,19 +383,28 @@ describe('measureSweep', () => { describe('estimateScope', () => { const counts = { 'a.ts': 100, 'b.ts': 100, 'new.ts': 50 }; - const lineCount = (file) => counts[file] ?? null; - const entry = (file, start, end) => (start - ? { path: file, range: true, start, end, text: `${file}:${start}-${end}` } - : { path: file, range: false, start: 0, end: 0, text: file }); + const lineCount = file => counts[file] ?? null; + const entry = (file, start, end) => + start + ? { path: file, range: true, start, end, text: `${file}:${start}-${end}` } + : { path: file, range: false, start: 0, end: 0, text: file }; const history = { version: 2, files: { 'a.ts': 600, 'b.ts': 20, 'gone.ts': 999 }, - lines: { 'a.ts': [[10, 3, 500], [80, 1, 100]], 'b.ts': [[10, 2, 20]] }, + lines: { + 'a.ts': [ + [10, 3, 500], + [80, 1, 100], + ], + 'b.ts': [[10, 2, 20]], + }, }; it('costs a measured file at what it took, and a range at what its lines took', () => { - assert.deepEqual(estimateScope([entry('a.ts'), entry('b.ts'), entry('a.ts', 5, 15)], history, lineCount), - [600, 20, 500]); + assert.deepEqual( + estimateScope([entry('a.ts'), entry('b.ts'), entry('a.ts', 5, 15)], history, lineCount), + [600, 20, 500], + ); }); it("costs new lines at the file's average, and a file the sweep never saw at the sweep's", () => { @@ -325,25 +423,37 @@ describe('estimateScope', () => { assert.equal(estimateScope([entry('a.ts')], missing, lineCount), null); } assert.equal(estimateScope([entry('new.ts')], { files: { 'a.ts': 1e308, 'b.ts': 1e308 } }, lineCount), null); - assert.equal(estimateScope([entry('a.ts'), entry('b.ts')], { files: { 'a.ts': 1e308, 'b.ts': 1e308 } }, - lineCount), null); + assert.equal( + estimateScope([entry('a.ts'), entry('b.ts')], { files: { 'a.ts': 1e308, 'b.ts': 1e308 } }, lineCount), + null, + ); const odd = { files: { 'a.ts': 600 }, lines: { 'a.ts': [null, [10, 1, 'x'], [12, 1, 30]] } }; assert.deepEqual(estimateScope([entry('a.ts', 1, 20)], odd, lineCount), [120]); }); }); describe('planScope', () => { - const entry = (file, lines, range) => (range - ? { path: file, range: true, start: range[0], end: range[1], text: `${file}:${range[0]}-${range[1]}` } - : { path: file, range: false, start: 0, end: 0, text: file, lines }); - const paths = (bins) => bins.map((bin) => bin.entries.map(({ text }) => text)); + const entry = (file, lines, range) => + range + ? { path: file, range: true, start: range[0], end: range[1], text: `${file}:${range[0]}-${range[1]}` } + : { path: file, range: false, start: 0, end: 0, text: file, lines }; + const paths = bins => bins.map(bin => bin.entries.map(({ text }) => text)); it('balances files of like size but unlike cost by cost', () => { const entries = [entry('a.ts'), entry('b.ts'), entry('c.ts'), entry('d.ts')]; - assert.deepEqual(paths(planScope(entries, [100, 100, 90, 90], 2)), [['a.ts', 'c.ts'], ['b.ts', 'd.ts']]); + assert.deepEqual(paths(planScope(entries, [100, 100, 90, 90], 2)), [ + ['a.ts', 'c.ts'], + ['b.ts', 'd.ts'], + ]); const bins = planScope(entries, [6000, 300, 5800, 290], 2); - assert.deepEqual(paths(bins), [['a.ts', 'd.ts'], ['b.ts', 'c.ts']]); - assert.deepEqual(bins.map(({ weight }) => weight), [6290, 6100]); + assert.deepEqual(paths(bins), [ + ['a.ts', 'd.ts'], + ['b.ts', 'c.ts'], + ]); + assert.deepEqual( + bins.map(({ weight }) => weight), + [6290, 6100], + ); }); it('splits a file heavier than its share across shards by range, and never cuts a range', () => { diff --git a/.github/workflows/node-quality-gates.yml b/.github/workflows/node-quality-gates.yml index dd90835..b34f5d0 100644 --- a/.github/workflows/node-quality-gates.yml +++ b/.github/workflows/node-quality-gates.yml @@ -394,7 +394,8 @@ jobs: import crypto from 'node:crypto'; import path from 'node:path'; import { execFileSync } from 'node:child_process'; - const { escape, estimateScope, normalise, planScope } = await import(process.env.MUTATION_REPORTS); + const { escapePath, estimateScope, normalise, planScope } = + await import(process.env.MUTATION_REPORTS); const fail = (message) => { console.log(`::error::${message}`); @@ -522,7 +523,8 @@ jobs: // A leading ! would read as an exclusion, so such a path starts with ./ instead. const include = bins.map((bin, index) => ({ shard: index + 1, - mutate: bin.entries.map((entry) => escape(entry.path) + entry.text.slice(entry.path.length)) + mutate: bin.entries + .map((entry) => escapePath(entry.path) + entry.text.slice(entry.path.length)) .join(','), })); output('empty', 'false'); @@ -1157,7 +1159,7 @@ jobs: import fs from 'node:fs'; import path from 'node:path'; import { execFileSync } from 'node:child_process'; - const { escape, expandMutate, packFiles } = await import(process.env.MUTATION_REPORTS); + const { escapePath, expandMutate, packFiles } = await import(process.env.MUTATION_REPORTS); // Predicted mutation minutes per shard above which the sweep should take more shards. const TARGET_MINUTES = 120; @@ -1223,7 +1225,7 @@ jobs: const include = bins.map((bin, index) => ({ shard: index + 1, - mutate: bin.files.map(escape).join(','), + mutate: bin.files.map(escapePath).join(','), predicted: minutes(bin), })); output('matrix', JSON.stringify({ include })); diff --git a/.qlty/configs/biome.json b/.qlty/configs/biome.json new file mode 100644 index 0000000..ada1274 --- /dev/null +++ b/.qlty/configs/biome.json @@ -0,0 +1,8 @@ +{ + "$schema": "https://biomejs.dev/schemas/2.5.6/schema.json", + "root": true, + "extends": ["./biome.shared.json"], + "files": { + "includes": ["**", "!**/node_modules/**", "!**/vendor/**", "!**/.qlty/**"] + } +} diff --git a/.qlty/hooks/pre-push.sh b/.qlty/hooks/pre-push.sh index f128051..c68451c 100755 --- a/.qlty/hooks/pre-push.sh +++ b/.qlty/hooks/pre-push.sh @@ -1,6 +1,2 @@ #!/bin/sh -qlty check \ - --trigger pre-push \ - --upstream-from-pre-push \ - --no-formatters \ - --skip-errored-plugins +qlty check --trigger pre-push --upstream-from-pre-push --no-formatters --skip-errored-plugins diff --git a/.qlty/qlty.toml b/.qlty/qlty.toml index 0f6f332..7e9822f 100644 --- a/.qlty/qlty.toml +++ b/.qlty/qlty.toml @@ -51,3 +51,7 @@ drivers = [ [[plugin]] name = "trufflehog" + +[[plugin]] +name = "biome" +version = "2.5.6"