Skip to content
Open
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
12 changes: 7 additions & 5 deletions lib/internal/test_runner/coverage.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ class TestCoverage {
#sourceLines = new SafeMap();
#typeScriptLines = new SafeSet();
#skipCache = new SafeMap();
#sourceMappedUrls = new SafeSet();

getLines(fileUrl, source) {
// Split the file source into lines. Make sure the lines maintain their
Expand Down Expand Up @@ -259,6 +260,7 @@ class TestCoverage {
continue;
}

const isSourceMapped = this.#sourceMappedUrls.has(url);

for (let j = 0; j < functions.length; ++j) {
const { isBlockCoverage, ranges } = functions[j];
Expand All @@ -270,7 +272,7 @@ class TestCoverage {

// Add some useful data to the range. The test runner has read these ranges
// from a file, so we own the data structures and can do what we want.
ObjectAssign(range, mapRangeToLines(range, lines));
ObjectAssign(range, mapRangeToLines(range, lines, isSourceMapped));

if (isBlockCoverage) {
ArrayPrototypePush(branchReports, {
Expand Down Expand Up @@ -541,9 +543,6 @@ class TestCoverage {
// The range is not mappable. Skip it.
continue;
}
for (let l = startEntry.originalLine; l <= endEntry.originalLine; l++) {
mappedLines[l].count = count;
}

ArrayPrototypePush(newRanges, {
__proto__: null, startOffset: mappedStartOffset, endOffset: mappedEndOffset, count,
Expand All @@ -554,6 +553,7 @@ class TestCoverage {
// No mappable ranges. Skip the function.
continue;
}
this.#sourceMappedUrls.add(newUrl);
const newScript = newResult.get(newUrl) ?? { __proto__: null, url: newUrl, functions: [] };
ArrayPrototypePush(newScript.functions, { __proto__: null, functionName, ranges: newRanges, isBlockCoverage });
newResult.set(newUrl, newScript);
Expand Down Expand Up @@ -697,7 +697,7 @@ function setupCoverage(options) {
);
}

function mapRangeToLines(range, lines) {
function mapRangeToLines(range, lines, isSourceMapped) {
const { startOffset, endOffset, count } = range;
const mappedLines = [];
let ignoredLines = 0;
Expand All @@ -715,6 +715,8 @@ function mapRangeToLines(range, lines) {
// then mark that line as not covered.
if (startOffset <= line.startOffset && endOffset >= line.endOffset) {
line.count = count;
} else if (isSourceMapped && count > 0) {
line.count = MathMax(line.count, count);
}

ArrayPrototypePush(mappedLines, line);
Expand Down
156 changes: 156 additions & 0 deletions test/parallel/test-runner-coverage-source-map.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
'use strict';
const common = require('../common');
const assert = require('node:assert');
const fs = require('node:fs');
const path = require('node:path');
const { pathToFileURL } = require('url');
const fixtures = require('../common/fixtures');
const tmpdir = require('../common/tmpdir');
common.skipIfInspectorDisabled();

const { describe, it } = require('node:test');
Expand Down Expand Up @@ -147,4 +151,156 @@ describe('Coverage with source maps', async () => {
t.assert.strictEqual(spawned.code, 1);
});
}

await it('should report consistent source-mapped line counts regardless of merge order', async () => {
tmpdir.refresh();

const source = [
'/**',
' Adds two numbers.',
'*/',
'export function add (a: number, b: number): number {',
' return a + b',
'}',
'',
].join('\n');
const sourceMap = Buffer.from(JSON.stringify({
version: 3,
sources: ['lib.ts'],
sourcesContent: [source],
mappings: 'AAGO,SAAS,IAAK,GAAW,GAAmB;AACjD,SAAS,IAAI;AACb;',
names: [],
})).toString('base64');

fs.writeFileSync(
tmpdir.resolve('lib.js'),
'function add(a, b) {\n' +
' return a + b;\n' +
'}\n' +
'export {\n' +
' add\n' +
'};\n' +
`//# sourceMappingURL=data:application/json;base64,${sourceMap}\n`,
);
fs.writeFileSync(
tmpdir.resolve('calls.test.mjs'),
"import test from 'node:test';\n" +
"import assert from 'node:assert/strict';\n" +
"import { add } from './lib.js';\n" +
"test('add', () => assert.strictEqual(add(1, 2), 3));\n",
);
fs.writeFileSync(
tmpdir.resolve('imports.test.mjs'),
"import test from 'node:test';\n" +
"import './lib.js';\n" +
"test('import', () => {});\n",
);

const covCallsDir = tmpdir.resolve('cov-calls');
const covImportsDir = tmpdir.resolve('cov-imports');
fs.mkdirSync(covCallsDir);
fs.mkdirSync(covImportsDir);

const captureFlags = [
'--enable-source-maps',
'--test',
'--experimental-test-coverage',
'--test-coverage-include=lib.*',
'--no-experimental-strip-types',
];

const callsRun = await common.spawnPromisified(
process.execPath,
[...captureFlags, 'calls.test.mjs'],
{ cwd: tmpdir.path, env: { ...process.env, NODE_V8_COVERAGE: covCallsDir } },
);
assert.strictEqual(callsRun.code, 0, callsRun.stderr);

const importsRun = await common.spawnPromisified(
process.execPath,
[...captureFlags, 'imports.test.mjs'],
{ cwd: tmpdir.path, env: { ...process.env, NODE_V8_COVERAGE: covImportsDir } },
);
assert.strictEqual(importsRun.code, 0, importsRun.stderr);

function findLibCoverage(dir) {
for (const name of fs.readdirSync(dir)) {
if (!name.startsWith('coverage-') || !name.endsWith('.json')) continue;
const data = JSON.parse(fs.readFileSync(path.join(dir, name), 'utf8'));
if (data.result?.some((entry) => entry.url?.endsWith('/lib.js'))) {
return path.join(dir, name);
}
}
assert.fail(`Missing coverage payload for lib.js in ${dir}`);
}

const callsCovFile = findLibCoverage(covCallsDir);
const importsCovFile = findLibCoverage(covImportsDir);

const replayScript = `
const assert = require('node:assert');
const fs = require('node:fs');
const { TestCoverage } = require('internal/test_runner/coverage');
const cwd = ${JSON.stringify(tmpdir.path)};
const files = [${JSON.stringify(callsCovFile)}, ${JSON.stringify(importsCovFile)}];
function summarize(order) {
const tc = new TestCoverage(cwd, undefined, {
cwd,
sourceMaps: true,
coverageIncludeGlobs: ['lib.*'],
});
tc.getCoverageFromDirectory = () => {
const merged = new Map();
for (const file of order) {
const cov = JSON.parse(fs.readFileSync(file, 'utf8'));
tc.mergeCoverage(merged, tc.mapCoverageWithSourceMap(cov));
}
return Array.from(merged.values());
};
return tc.summary();
}
const first = summarize(files);
const second = summarize([...files].reverse());
assert.strictEqual(first.files.length, 1);
assert.strictEqual(first.files[0].coveredLineCount, 3);
assert.strictEqual(first.files[0].totalLineCount, 6);
assert.ok(first.files[0].lines[3].count > 0);
assert.deepStrictEqual(second.files, first.files);
`;

const replayRun = await common.spawnPromisified(
process.execPath,
['--expose-internals', '-e', replayScript],
{ cwd: tmpdir.path },
);
assert.strictEqual(replayRun.stderr, '');
assert.strictEqual(replayRun.code, 0);

const combinedRun = await common.spawnPromisified(
process.execPath,
[
'--enable-source-maps',
'--test',
'--experimental-test-coverage',
'--test-coverage-include=lib.*',
'--test-reporter',
'tap',
'--no-experimental-strip-types',
'calls.test.mjs',
'imports.test.mjs',
],
{ cwd: tmpdir.path },
);
assert.strictEqual(combinedRun.stderr, '');
assert.strictEqual(combinedRun.code, 0);
assert.ok(combinedRun.stdout.includes(generateReport([
'# ----------------------------------------------------------',
'# file | line % | branch % | funcs % | uncovered lines',
'# ----------------------------------------------------------',
'# lib.ts | 50.00 | 100.00 | 100.00 | 1-3',
'# ----------------------------------------------------------',
'# all files | 50.00 | 100.00 | 100.00 | ',
'# ----------------------------------------------------------',
])), combinedRun.stdout);
});
}).then(common.mustCall());
Loading