summaryrefslogtreecommitdiff
path: root/test/parallel/test-async-wrap-throw-from-callback.js
blob: 86abebd7d3a8105f32be8f4b26fab2867dc23232 (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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
'use strict';

const common = require('../common');
if (!common.hasCrypto) {
  common.skip('missing crypto');
  return;
}

const async_wrap = process.binding('async_wrap');
const assert = require('assert');
const crypto = require('crypto');
const domain = require('domain');
const spawn = require('child_process').spawn;
const callbacks = [ 'init', 'pre', 'post', 'destroy' ];
const toCall = process.argv[2];
let msgCalled = 0;
let msgReceived = 0;

function init() {
  if (toCall === 'init')
    throw new Error('init');
}
function pre() {
  if (toCall === 'pre')
    throw new Error('pre');
}
function post() {
  if (toCall === 'post')
    throw new Error('post');
}
function destroy() {
  if (toCall === 'destroy')
    throw new Error('destroy');
}

if (typeof process.argv[2] === 'string') {
  async_wrap.setupHooks({ init, pre, post, destroy });
  async_wrap.enable();

  process.on('uncaughtException', common.mustNotCall());

  const d = domain.create();
  d.on('error', common.mustNotCall());
  d.run(() => {
    // Using randomBytes because timers are not yet supported.
    crypto.randomBytes(0, () => { });
  });

} else {

  process.on('exit', (code) => {
    assert.strictEqual(msgCalled, callbacks.length);
    assert.strictEqual(msgCalled, msgReceived);
  });

  callbacks.forEach((item) => {
    msgCalled++;

    const child = spawn(process.execPath, [__filename, item]);
    let errstring = '';

    child.stderr.on('data', (data) => {
      errstring += data.toString();
    });

    child.on('close', (code) => {
      if (errstring.includes('Error: ' + item))
        msgReceived++;

      assert.strictEqual(code, 1, `${item} closed with code ${code}`);
    });
  });
}