summaryrefslogtreecommitdiff
path: root/test/parallel/test-http-agent-abort-controller.js
blob: c5ece3ab353bf03ee1e5b6b7067aa4304d283d1c (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');
const assert = require('assert');
const http = require('http');
const Agent = http.Agent;
const { getEventListeners, once } = require('events');
const agent = new Agent();
const server = http.createServer();

server.listen(0, common.mustCall(async () => {
  const port = server.address().port;
  const host = 'localhost';
  const options = {
    port: port,
    host: host,
    _agentKey: agent.getName({ port, host })
  };

  async function postCreateConnection() {
    const ac = new AbortController();
    const { signal } = ac;
    const connection = agent.createConnection({ ...options, signal });
    assert.strictEqual(getEventListeners(signal, 'abort').length, 1);
    ac.abort();
    const [err] = await once(connection, 'error');
    assert.strictEqual(err?.name, 'AbortError');
  }

  async function preCreateConnection() {
    const ac = new AbortController();
    const { signal } = ac;
    ac.abort();
    const connection = agent.createConnection({ ...options, signal });
    const [err] = await once(connection, 'error');
    assert.strictEqual(err?.name, 'AbortError');
  }

  async function agentAsParam() {
    const ac = new AbortController();
    const { signal } = ac;
    const request = http.get({
      port: server.address().port,
      path: '/hello',
      agent: agent,
      signal,
    });
    assert.strictEqual(getEventListeners(signal, 'abort').length, 1);
    ac.abort();
    const [err] = await once(request, 'error');
    assert.strictEqual(err?.name, 'AbortError');
  }

  async function agentAsParamPreAbort() {
    const ac = new AbortController();
    const { signal } = ac;
    ac.abort();
    const request = http.get({
      port: server.address().port,
      path: '/hello',
      agent: agent,
      signal,
    });
    assert.strictEqual(getEventListeners(signal, 'abort').length, 0);
    const [err] = await once(request, 'error');
    assert.strictEqual(err?.name, 'AbortError');
  }

  await postCreateConnection();
  await preCreateConnection();
  await agentAsParam();
  await agentAsParamPreAbort();
  server.close();
}));