|
1 | 1 | 'use strict';
|
2 |
| -const common = require('../common'); |
3 | 2 |
|
4 |
| -// Test that `req.setTimeout` will fired exactly once. |
| 3 | +// Test that the `'timeout'` event is emitted exactly once if the `timeout` |
| 4 | +// option and `request.setTimeout()` are used together. |
5 | 5 |
|
6 |
| -const assert = require('assert'); |
7 |
| -const http = require('http'); |
| 6 | +const { expectsError, mustCall } = require('../common'); |
| 7 | +const { strictEqual } = require('assert'); |
| 8 | +const { createServer, get } = require('http'); |
8 | 9 |
|
9 |
| -const HTTP_CLIENT_TIMEOUT = 2000; |
10 |
| - |
11 |
| -const options = { |
12 |
| - method: 'GET', |
13 |
| - port: undefined, |
14 |
| - host: '127.0.0.1', |
15 |
| - path: '/', |
16 |
| - timeout: HTTP_CLIENT_TIMEOUT, |
17 |
| -}; |
18 |
| - |
19 |
| -const server = http.createServer(() => { |
| 10 | +const server = createServer(() => { |
20 | 11 | // Never respond.
|
21 | 12 | });
|
22 | 13 |
|
23 |
| -server.listen(0, options.host, function() { |
24 |
| - doRequest(); |
25 |
| -}); |
26 |
| - |
27 |
| -function doRequest() { |
28 |
| - options.port = server.address().port; |
29 |
| - const req = http.request(options); |
30 |
| - req.setTimeout(HTTP_CLIENT_TIMEOUT / 2); |
31 |
| - req.on('error', () => { |
32 |
| - // This space is intentionally left blank. |
| 14 | +server.listen(0, mustCall(() => { |
| 15 | + const req = get({ |
| 16 | + port: server.address().port, |
| 17 | + timeout: 2000, |
33 | 18 | });
|
34 |
| - req.on('close', common.mustCall(() => server.close())); |
35 | 19 |
|
36 |
| - let timeout_events = 0; |
37 |
| - req.on('timeout', common.mustCall(() => { |
38 |
| - timeout_events += 1; |
| 20 | + req.setTimeout(1000); |
| 21 | + |
| 22 | + req.on('socket', mustCall((socket) => { |
| 23 | + strictEqual(socket.timeout, 2000); |
| 24 | + |
| 25 | + socket.on('connect', mustCall(() => { |
| 26 | + strictEqual(socket.timeout, 1000); |
| 27 | + |
| 28 | + // Reschedule the timer to not wait 1 sec and make the test finish faster. |
| 29 | + socket.setTimeout(10); |
| 30 | + strictEqual(socket.timeout, 10); |
| 31 | + })); |
| 32 | + })); |
| 33 | + |
| 34 | + req.on('error', expectsError({ |
| 35 | + type: Error, |
| 36 | + code: 'ECONNRESET', |
| 37 | + message: 'socket hang up' |
39 | 38 | }));
|
40 |
| - req.end(); |
41 | 39 |
|
42 |
| - setTimeout(function() { |
| 40 | + req.on('close', mustCall(() => { |
| 41 | + server.close(); |
| 42 | + })); |
| 43 | + |
| 44 | + req.on('timeout', mustCall(() => { |
| 45 | + strictEqual(req.socket.listenerCount('timeout'), 0); |
43 | 46 | req.destroy();
|
44 |
| - assert.strictEqual(timeout_events, 1); |
45 |
| - }, common.platformTimeout(HTTP_CLIENT_TIMEOUT)); |
46 |
| -} |
| 47 | + })); |
| 48 | +})); |
0 commit comments