|
| 1 | +'use strict'; |
| 2 | +const common = require('../common'); |
| 3 | +const assert = require('assert'); |
| 4 | +const dgram = require('dgram'); |
| 5 | +const dns = require('dns'); |
| 6 | + |
| 7 | +// Monkey patch dns.lookup() so that it always fails. |
| 8 | +dns.lookup = function(address, family, callback) { |
| 9 | + process.nextTick(() => { callback(new Error('fake DNS')); }); |
| 10 | +}; |
| 11 | + |
| 12 | +const socket = dgram.createSocket('udp4'); |
| 13 | +let dnsFailures = 0; |
| 14 | +let sendFailures = 0; |
| 15 | + |
| 16 | +process.on('exit', () => { |
| 17 | + assert.strictEqual(dnsFailures, 3); |
| 18 | + assert.strictEqual(sendFailures, 3); |
| 19 | +}); |
| 20 | + |
| 21 | +socket.on('error', (err) => { |
| 22 | + if (/^Error: fake DNS$/.test(err)) { |
| 23 | + // The DNS lookup should fail since it is monkey patched. At that point in |
| 24 | + // time, the send queue should be populated with the send() operation. There |
| 25 | + // should also be two listeners - this function and the dgram internal one |
| 26 | + // time error handler. |
| 27 | + dnsFailures++; |
| 28 | + assert(Array.isArray(socket._queue)); |
| 29 | + assert.strictEqual(socket._queue.length, 1); |
| 30 | + assert.strictEqual(socket.listenerCount('error'), 2); |
| 31 | + return; |
| 32 | + } |
| 33 | + |
| 34 | + if (/^Error: Unable to send data$/.test(err)) { |
| 35 | + // On error, the queue should be destroyed and this function should be |
| 36 | + // the only listener. |
| 37 | + sendFailures++; |
| 38 | + assert.strictEqual(socket._queue, undefined); |
| 39 | + assert.strictEqual(socket.listenerCount('error'), 1); |
| 40 | + return; |
| 41 | + } |
| 42 | + |
| 43 | + common.fail(`Unexpected error: ${err}`); |
| 44 | +}); |
| 45 | + |
| 46 | +// Initiate a few send() operations, which will fail. |
| 47 | +socket.send('foobar', common.PORT, 'localhost'); |
| 48 | + |
| 49 | +process.nextTick(() => { |
| 50 | + socket.send('foobar', common.PORT, 'localhost'); |
| 51 | +}); |
| 52 | + |
| 53 | +setImmediate(() => { |
| 54 | + socket.send('foobar', common.PORT, 'localhost'); |
| 55 | +}); |
0 commit comments