Skip to content

Commit ab2ddb2

Browse files
committed
Add worker termination test
1 parent c6b1279 commit ab2ddb2

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

ts/test/test-worker-threads.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// eslint-disable-next-line node/no-unsupported-features/node-builtins
22
import {execFile} from 'child_process';
33
import {promisify} from 'util';
4+
import {Worker} from 'worker_threads';
45

56
const exec = promisify(execFile);
67

@@ -11,4 +12,34 @@ describe('Worker Threads', () => {
1112
const nbWorkers = 2;
1213
return exec('node', ['./out/test/worker.js', String(nbWorkers)]);
1314
});
15+
16+
it('should not crash when worker is terminated', async function () {
17+
this.timeout(30000);
18+
const nruns = 5;
19+
const concurrentWorkers = 20;
20+
for (let i = 0; i < nruns; i++) {
21+
const workers = [];
22+
for (let j = 0; j < concurrentWorkers; j++) {
23+
const worker = new Worker('./out/test/worker2.js');
24+
worker.postMessage('hello');
25+
26+
worker.on('message', () => {
27+
worker.terminate();
28+
});
29+
30+
workers.push(
31+
new Promise<void>((resolve, reject) => {
32+
worker.on('exit', exitCode => {
33+
if (exitCode === 1) {
34+
resolve();
35+
} else {
36+
reject(new Error('Worker exited with code 0'));
37+
}
38+
});
39+
})
40+
);
41+
}
42+
await Promise.all(workers);
43+
}
44+
});
1445
});

ts/test/worker2.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import {parentPort} from 'node:worker_threads';
2+
import {time} from '../src/index';
3+
4+
const delay = (ms: number) => new Promise(res => setTimeout(res, ms));
5+
6+
const DURATION_MILLIS = 1000;
7+
const INTERVAL_MICROS = 10000;
8+
const withContexts =
9+
process.platform === 'darwin' || process.platform === 'linux';
10+
11+
time.start({
12+
durationMillis: DURATION_MILLIS,
13+
intervalMicros: INTERVAL_MICROS,
14+
withContexts: withContexts,
15+
collectCpuTime: withContexts,
16+
collectAsyncId: false,
17+
});
18+
19+
parentPort?.on('message', () => {
20+
delay(50).then(() => {
21+
parentPort?.postMessage('hello');
22+
});
23+
});

0 commit comments

Comments
 (0)