Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test_runner: watch mode improvments #48259

Closed
wants to merge 2 commits into from
Closed
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
4 changes: 4 additions & 0 deletions doc/api/test.md
Original file line number Diff line number Diff line change
Expand Up @@ -1539,6 +1539,10 @@ This event is only emitted if `--test` flag is passed.
Emitted when a running test writes to `stdout`.
This event is only emitted if `--test` flag is passed.

### Event: `'test:watch:drained'`

Emitted when no more tests are queued for execution in watch mode.

## Class: `TestContext`

<!-- YAML
Expand Down
40 changes: 26 additions & 14 deletions lib/internal/test_runner/runner.js
Original file line number Diff line number Diff line change
Expand Up @@ -335,15 +335,13 @@ class FileTest extends Test {
}
}

const runningProcesses = new SafeMap();
const runningSubtests = new SafeMap();

function runTestFile(path, root, inspectPort, filesWatcher, testNamePatterns) {
const watchMode = filesWatcher != null;
const subtest = root.createSubtest(FileTest, path, async (t) => {
const args = getRunArgs({ path, inspectPort, testNamePatterns });
const stdio = ['pipe', 'pipe', 'pipe'];
const env = { ...process.env, NODE_TEST_CONTEXT: 'child-v8' };
if (filesWatcher) {
if (watchMode) {
stdio.push('ipc');
env.WATCH_REPORT_DEPENDENCIES = '1';
}
Expand All @@ -352,11 +350,13 @@ function runTestFile(path, root, inspectPort, filesWatcher, testNamePatterns) {
}

const child = spawn(process.execPath, args, { signal: t.signal, encoding: 'utf8', env, stdio });
runningProcesses.set(path, child);
if (watchMode) {
filesWatcher.runningProcesses.set(path, child);
filesWatcher.watcher.watchChildProcessModules(child, path);
}

let err;

filesWatcher?.watchChildProcessModules(child, path);

child.on('error', (error) => {
err = error;
Expand Down Expand Up @@ -388,8 +388,14 @@ function runTestFile(path, root, inspectPort, filesWatcher, testNamePatterns) {
finished(child.stdout, { signal: t.signal }),
]);

runningProcesses.delete(path);
runningSubtests.delete(path);
if (watchMode) {
filesWatcher.runningProcesses.delete(path);
filesWatcher.runningSubtests.delete(path);
if (filesWatcher.runningSubtests.size === 0) {
root.reporter[kEmitMessage]('test:watch:drained');
}
}

if (code !== 0 || signal !== null) {
if (!err) {
const failureType = subtest.failedSubtests ? kSubtestsFailed : kTestCodeFailure;
Expand All @@ -409,10 +415,14 @@ function runTestFile(path, root, inspectPort, filesWatcher, testNamePatterns) {
return subtest.start();
}

function watchFiles(testFiles, root, inspectPort, testNamePatterns) {
const filesWatcher = new FilesWatcher({ throttle: 500, mode: 'filter' });
filesWatcher.on('changed', ({ owners }) => {
filesWatcher.unfilterFilesOwnedBy(owners);
function watchFiles(testFiles, root, inspectPort, signal, testNamePatterns) {
const runningProcesses = new SafeMap();
const runningSubtests = new SafeMap();
const watcher = new FilesWatcher({ throttle: 500, mode: 'filter', signal });
const filesWatcher = { __proto__: null, watcher, runningProcesses, runningSubtests };

watcher.on('changed', ({ owners }) => {
watcher.unfilterFilesOwnedBy(owners);
PromisePrototypeThen(SafePromiseAllReturnVoid(testFiles, async (file) => {
if (!owners.has(file)) {
return;
Expand All @@ -432,6 +442,8 @@ function watchFiles(testFiles, root, inspectPort, testNamePatterns) {
triggerUncaughtException(error, true /* fromPromise */);
}));
});
signal?.addEventListener('abort', () => root.postRun(), { __proto__: null, once: true });

return filesWatcher;
}

Expand Down Expand Up @@ -474,14 +486,14 @@ function run(options) {
let postRun = () => root.postRun();
let filesWatcher;
if (watch) {
filesWatcher = watchFiles(testFiles, root, inspectPort, testNamePatterns);
filesWatcher = watchFiles(testFiles, root, inspectPort, signal, testNamePatterns);
postRun = undefined;
}
const runFiles = () => {
root.harness.bootstrapComplete = true;
return SafePromiseAllSettledReturnVoid(testFiles, (path) => {
const subtest = runTestFile(path, root, inspectPort, filesWatcher, testNamePatterns);
runningSubtests.set(path, subtest);
filesWatcher?.runningSubtests.set(path, subtest);
return subtest;
});
};
Expand Down
8 changes: 6 additions & 2 deletions lib/internal/watch_mode/files_watcher.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,18 @@ class FilesWatcher extends EventEmitter {
#ownerDependencies = new SafeMap();
#throttle;
#mode;
#signal;

constructor({ throttle = 500, mode = 'filter' } = kEmptyObject) {
constructor({ throttle = 500, mode = 'filter', signal } = kEmptyObject) {
super();

validateNumber(throttle, 'options.throttle', 0, TIMEOUT_MAX);
validateOneOf(mode, 'options.mode', ['filter', 'all']);
this.#throttle = throttle;
this.#mode = mode;
this.#signal = signal;

signal?.addEventListener('abort', () => this.clear(), { __proto__: null, once: true });
}

#isPathWatched(path) {
Expand Down Expand Up @@ -89,7 +93,7 @@ class FilesWatcher extends EventEmitter {
if (this.#isPathWatched(path)) {
return;
}
const watcher = watch(path, { recursive });
const watcher = watch(path, { recursive, signal: this.#signal });
watcher.on('change', (eventType, fileName) => this
.#onChange(recursive ? resolve(path, fileName) : path));
this.#watchers.set(path, { handle: watcher, recursive });
Expand Down
25 changes: 25 additions & 0 deletions test/parallel/test-runner-run.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -117,4 +117,29 @@ describe('require(\'node:test\').run', { concurrency: true }, () => {
assert.strictEqual(result[2], 'ok 1 - this should be skipped # SKIP test name does not match pattern\n');
assert.strictEqual(result[5], 'ok 2 - this should be executed\n');
});

it('should stop watch mode when abortSignal aborts', async () => {
const controller = new AbortController();
const result = await run({ files: [join(testFixtures, 'test/random.cjs')], watch: true, signal: controller.signal })
.compose(async function* (source) {
for await (const chunk of source) {
if (chunk.type === 'test:pass') {
controller.abort();
yield chunk.data.name;
}
}
})
.toArray();
assert.deepStrictEqual(result, ['this should pass']);
});

it('should emit "test:watch:drained" event on watch mode', async () => {
const controller = new AbortController();
await run({ files: [join(testFixtures, 'test/random.cjs')], watch: true, signal: controller.signal })
.on('data', function({ type }) {
if (type === 'test:watch:drained') {
controller.abort();
}
});
});
});