summaryrefslogtreecommitdiff
path: root/test/parallel/test-worker-exit-code.js
blob: 6107cd0316b250e27217b8e75f65b28f67f4cf18 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
'use strict';
const common = require('../common');

// This test checks that Worker has correct exit codes on parent side
// in multiple situations.

const assert = require('assert');
const worker = require('worker_threads');
const { Worker, parentPort } = worker;

const testCases = require('../fixtures/process-exit-code-cases');

// Do not use isMainThread so that this test itself can be run inside a Worker.
if (!process.env.HAS_STARTED_WORKER) {
  process.env.HAS_STARTED_WORKER = 1;
  parent();
} else {
  if (!parentPort) {
    console.error('Parent port must not be null');
    process.exit(100);
    return;
  }
  parentPort.once('message', (msg) => testCases[msg].func());
}

function parent() {
  const test = (arg, name = 'worker', exit, error = null) => {
    const w = new Worker(__filename);
    w.on('exit', common.mustCall((code) => {
      assert.strictEqual(
        code, exit,
        `wrong exit for ${arg}-${name}\nexpected:${exit} but got:${code}`);
      console.log(`ok - ${arg} exited with ${exit}`);
    }));
    if (error) {
      w.on('error', common.mustCall((err) => {
        console.log(err);
        assert(error.test(err),
               `wrong error for ${arg}\nexpected:${error} but got:${err}`);
      }));
    }
    w.postMessage(arg);
  };

  testCases.forEach((tc, i) => test(i, tc.func.name, tc.result, tc.error));
}