• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2const common = require('../common');
3
4// This test checks that Worker has correct exit codes on parent side
5// in multiple situations.
6
7const assert = require('assert');
8const worker = require('worker_threads');
9const { Worker, parentPort } = worker;
10
11const { getTestCases } = require('../fixtures/process-exit-code-cases');
12const testCases = getTestCases(true);
13
14// Do not use isMainThread so that this test itself can be run inside a Worker.
15if (!process.env.HAS_STARTED_WORKER) {
16  process.env.HAS_STARTED_WORKER = 1;
17  parent();
18} else {
19  if (!parentPort) {
20    console.error('Parent port must not be null');
21    process.exit(100);
22    return;
23  }
24  parentPort.once('message', (msg) => testCases[msg].func());
25}
26
27function parent() {
28  const test = (arg, name = 'worker', exit, error = null) => {
29    const w = new Worker(__filename);
30    w.on('exit', common.mustCall((code) => {
31      assert.strictEqual(
32        code, exit,
33        `wrong exit for ${arg}-${name}\nexpected:${exit} but got:${code}`);
34      console.log(`ok - ${arg} exited with ${exit}`);
35    }));
36    if (error) {
37      w.on('error', common.mustCall((err) => {
38        console.log(err);
39        assert.match(String(err), error);
40      }));
41    }
42    w.postMessage(arg);
43  };
44
45  testCases.forEach((tc, i) => test(i, tc.func.name, tc.result, tc.error));
46}
47