summaryrefslogtreecommitdiff
path: root/test/sequential/test-dgram-implicit-bind-failure.js
blob: d77db12618f3bcca08203c97350e85a9e749bc20 (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
// Flags: --expose-internals
'use strict';
const common = require('../common');
const assert = require('assert');
const dgram = require('dgram');
const dns = require('dns');
const { kStateSymbol } = require('internal/dgram');

// Monkey patch dns.lookup() so that it always fails.
dns.lookup = function(address, family, callback) {
  process.nextTick(() => { callback(new Error('fake DNS')); });
};

const socket = dgram.createSocket('udp4');
let dnsFailures = 0;
let sendFailures = 0;

process.on('exit', () => {
  assert.strictEqual(dnsFailures, 3);
  assert.strictEqual(sendFailures, 3);
});

socket.on('error', (err) => {
  if (/^Error: fake DNS$/.test(err)) {
    // The DNS lookup should fail since it is monkey patched. At that point in
    // time, the send queue should be populated with the send() operation. There
    // should also be two listeners - this function and the dgram internal one
    // time error handler.
    dnsFailures++;
    assert(Array.isArray(socket[kStateSymbol].queue));
    assert.strictEqual(socket[kStateSymbol].queue.length, 1);
    assert.strictEqual(socket.listenerCount('error'), 2);
    return;
  }

  if (err.code === 'ERR_SOCKET_CANNOT_SEND') {
    // On error, the queue should be destroyed and this function should be
    // the only listener.
    sendFailures++;
    assert.strictEqual(socket[kStateSymbol].queue, undefined);
    assert.strictEqual(socket.listenerCount('error'), 1);
    return;
  }

  assert.fail(`Unexpected error: ${err}`);
});

// Initiate a few send() operations, which will fail.
socket.send('foobar', common.PORT, 'localhost');

process.nextTick(() => {
  socket.send('foobar', common.PORT, 'localhost');
});

setImmediate(() => {
  socket.send('foobar', common.PORT, 'localhost');
});