summaryrefslogtreecommitdiff
path: root/test/parallel/test-http-client-timeout-option-with-agent.js
blob: 11a2db419c352905d6c20c7ee391b43e681514e9 (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
'use strict';
const common = require('../common');

// Test that when http request uses both timeout and agent,
// timeout will work as expected.

const assert = require('assert');
const http = require('http');

const HTTP_AGENT_TIMEOUT = 1000;
const HTTP_CLIENT_TIMEOUT = 3000;

const agent = new http.Agent({ timeout: HTTP_AGENT_TIMEOUT });
const options = {
  method: 'GET',
  port: undefined,
  host: '127.0.0.1',
  path: '/',
  timeout: HTTP_CLIENT_TIMEOUT,
  agent,
};

const server = http.createServer(() => {
  // Never respond.
});

server.listen(0, options.host, () => {
  doRequest();
});

function doRequest() {
  options.port = server.address().port;
  const start = process.hrtime.bigint();
  const req = http.request(options);
  req.on('error', () => {
    // This space is intentionally left blank.
  });
  req.on('close', common.mustCall(() => server.close()));

  let timeout_events = 0;
  req.on('timeout', common.mustCall(() => {
    timeout_events += 1;
    const duration = process.hrtime.bigint() - start;
    // The timeout event cannot be precisely timed. It will delay
    // some number of milliseconds.
    assert.ok(
      duration >= BigInt(HTTP_CLIENT_TIMEOUT * 1e6),
      `duration ${duration}ms less than timeout ${HTTP_CLIENT_TIMEOUT}ms`
    );
  }));
  req.end();

  setTimeout(() => {
    req.destroy();
    assert.strictEqual(timeout_events, 1);
    // Ensure the `timeout` event fired only once.
  }, common.platformTimeout(HTTP_CLIENT_TIMEOUT * 2));
}