aboutsummaryrefslogtreecommitdiff
path: root/test/bun.js/node-http.test.ts
blob: b3ab4072b3241e2001ebce327892d3f0c47a3199 (plain) (blame)
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
import { describe, expect, it, beforeAll, afterAll } from "bun:test";
import { createServer, request, get, Agent, globalAgent, Server } from "node:http";
import { createDoneDotAll } from "node-test-helpers";

describe("node:http", () => {
  describe("createServer", async () => {
    it("hello world", async () => {
      const server = createServer((req, res) => {
        res.writeHead(200, { "Content-Type": "text/plain" });
        res.end("Hello World");
      });
      server.listen(8123);

      const res = await fetch("http://localhost:8123");
      expect(await res.text()).toBe("Hello World");
      server.close();
    });

    it("request & response body streaming (large)", async () => {
      const bodyBlob = new Blob(["hello world", "hello world".repeat(9000)]);

      const input = await bodyBlob.text();

      const server = createServer((req, res) => {
        res.writeHead(200, { "Content-Type": "text/plain" });
        req.on("data", chunk => {
          res.write(chunk);
        });

        req.on("end", () => {
          res.end();
        });
      });
      server.listen(8124);

      const res = await fetch("http://localhost:8124", {
        method: "POST",
        body: bodyBlob,
      });

      const out = await res.text();
      expect(out).toBe(input);
      server.close();
    });

    it("request & response body streaming (small)", async () => {
      const bodyBlob = new Blob(["hello world", "hello world".repeat(4)]);

      const input = await bodyBlob.text();

      const server = createServer((req, res) => {
        res.writeHead(200, { "Content-Type": "text/plain" });
        req.on("data", chunk => {
          res.write(chunk);
        });

        req.on("end", () => {
          res.end();
        });
      });
      server.listen(8125);

      const res = await fetch("http://localhost:8125", {
        method: "POST",
        body: bodyBlob,
      });

      const out = await res.text();
      expect(out).toBe(input);
      server.close();
    });

    it("listen should return server", async () => {
      const server = createServer();
      const listenResponse = server.listen(8129);
      expect(listenResponse instanceof Server).toBe(true);
      expect(listenResponse).toBe(server);
      listenResponse.close();
    });
  });

  describe("request", () => {
    let server;
    let timer = null;
    beforeAll(() => {
      server = createServer((req, res) => {
        const reqUrl = new URL(req.url, `http://${req.headers.host}`);
        if (reqUrl.pathname) {
          if (reqUrl.pathname === "/redirect") {
            // Temporary redirect
            res.writeHead(301, {
              Location: "http://localhost:8126/redirected",
            });
            res.end("Got redirect!\n");
            return;
          }
          if (reqUrl.pathname === "/redirected") {
            res.writeHead(404, { "Content-Type": "text/plain" });
            res.end("Not Found");
            return;
          }
          if (reqUrl.pathname.includes("timeout")) {
            if (timer) clearTimeout(timer);
            timer = setTimeout(() => {
              res.end("Hello World");
              timer = null;
            }, 3000);
            return;
          }
          if (reqUrl.pathname === "/pathTest") {
            res.end("Path correct!\n");
            return;
          }
        }

        res.writeHead(200, { "Content-Type": "text/plain" });

        if (req.headers["x-test"]) {
          res.write(`x-test: ${req.headers["x-test"]}\n`);
        }

        // Check for body
        if (req.method === "POST") {
          req.on("data", chunk => {
            res.write(chunk);
          });

          req.on("end", () => {
            res.write("POST\n");
            res.end("Hello World");
          });
        } else {
          if (req.headers["X-Test"] !== undefined) {
            res.write(`X-Test: test\n`);
          }
          res.write("Maybe GET maybe not\n");
          res.end("Hello World");
        }
      });
      server.listen(8126);
    });
    afterAll(() => {
      server.close();
      if (timer) clearTimeout(timer);
    });

    it("should make a standard GET request when passed string as first arg", done => {
      const req = request("http://localhost:8126", res => {
        let data = "";
        res.setEncoding("utf8");
        res.on("data", chunk => {
          data += chunk;
        });
        res.on("end", () => {
          expect(data).toBe("Maybe GET maybe not\nHello World");
          done();
        });
        res.on("error", err => done(err));
      });
      req.end();
    });

    it("should make a POST request when provided POST method, even without a body", done => {
      const req = request({ host: "localhost", port: 8126, method: "POST" }, res => {
        let data = "";
        res.setEncoding("utf8");
        res.on("data", chunk => {
          data += chunk;
        });
        res.on("end", () => {
          expect(data).toBe("POST\nHello World");
          done();
        });
        res.on("error", err => done(err));
      });
      req.end();
    });

    it("should correctly handle a POST request with a body", done => {
      const req = request({ host: "localhost", port: 8126, method: "POST" }, res => {
        let data = "";
        res.setEncoding("utf8");
        res.on("data", chunk => {
          data += chunk;
        });
        res.on("end", () => {
          expect(data).toBe("Posting\nPOST\nHello World");
          done();
        });
        res.on("error", err => done(err));
      });
      req.write("Posting\n");
      req.end();
    });

    it("should noop request.setSocketKeepAlive without error", () => {
      const req = request("http://localhost:8126");
      req.setSocketKeepAlive(true, 1000);
      req.end();
      expect(true).toBe(true);
    });

    it("should allow us to set timeout with request.setTimeout or `timeout` in options", done => {
      const createDone = createDoneDotAll(done);
      const req1Done = createDone();
      const req2Done = createDone();

      // const start = Date.now();
      const req1 = request(
        {
          host: "localhost",
          port: 8126,
          path: "/timeout",
          timeout: 500,
        },
        res => {
          req1Done(new Error("Should not have received response"));
        },
      );
      req1.on("timeout", () => req1Done());

      const req2 = request(
        {
          host: "localhost",
          port: 8126,
          path: "/timeout",
        },
        res => {
          req2Done(new Error("Should not have received response"));
        },
      );

      req2.setTimeout(500, () => {
        req2Done();
      });
      req1.end();
      req2.end();
    });

    it("should correctly set path when path provided", done => {
      const createDone = createDoneDotAll(done);
      const req1Done = createDone();
      const req2Done = createDone();

      const req1 = request("http://localhost:8126/pathTest", res => {
        let data = "";
        res.setEncoding("utf8");
        res.on("data", chunk => {
          data += chunk;
        });
        res.on("end", () => {
          expect(data).toBe("Path correct!\n");
          req1Done();
        });
        res.on("error", err => req1Done(err));
      });

      const req2 = request("http://localhost:8126", { path: "/pathTest" }, res => {
        let data = "";
        res.setEncoding("utf8");
        res.on("data", chunk => {
          data += chunk;
        });
        res.on("end", () => {
          expect(data).toBe("Path correct!\n");
          req2Done();
        });
        res.on("error", err => req2Done(err));
      });

      req1.end();
      req2.end();

      expect(req1.path).toBe("/pathTest");
      expect(req2.path).toBe("/pathTest");
    });

    it("should emit response when response received", done => {
      const req = request("http://localhost:8126");

      req.on("response", res => {
        expect(res.statusCode).toBe(200);
        done();
      });
      req.end();
    });

    // NOTE: Node http.request doesn't follow redirects by default
    it("should handle redirects properly", done => {
      const req = request("http://localhost:8126/redirect", res => {
        let data = "";
        res.setEncoding("utf8");
        res.on("data", chunk => {
          data += chunk;
        });
        res.on("end", () => {
          expect(data).toBe("Got redirect!\n");
          done();
        });
        res.on("error", err => done(err));
      });
      req.end();
    });

    it("should correctly attach headers to request", done => {
      const req = request({ host: "localhost", port: 8126, headers: { "X-Test": "test" } }, res => {
        let data = "";
        res.setEncoding("utf8");
        res.on("data", chunk => {
          data += chunk;
        });
        res.on("end", () => {
          expect(data).toBe("x-test: test\nMaybe GET maybe not\nHello World");
          done();
        });
        res.on("error", err => done(err));
      });
      req.end();
      expect(req.getHeader("X-Test")).toBe("test");
    });

    it("should correct casing of method param", done => {
      const req = request({ host: "localhost", port: 8126, method: "get" }, res => {
        let data = "";
        res.setEncoding("utf8");
        res.on("data", chunk => {
          data += chunk;
        });
        res.on("end", () => {
          expect(data).toBe("Maybe GET maybe not\nHello World");
          done();
        });
        res.on("error", err => done(err));
      });
      req.end();
    });

    it("should allow for port as a string", done => {
      const req = request({ host: "localhost", port: "8126", method: "GET" }, res => {
        let data = "";
        res.setEncoding("utf8");
        res.on("data", chunk => {
          data += chunk;
        });
        res.on("end", () => {
          expect(data).toBe("Maybe GET maybe not\nHello World");
          done();
        });
        res.on("error", err => done(err));
      });
      req.end();
    });
  });

  describe("get", () => {
    let server;
    beforeAll(() => {
      server = createServer((req, res) => {
        res.writeHead(200, { "Content-Type": "text/plain" });
        res.end("Hello World");
      });
      server.listen(8127);
    });
    afterAll(() => {
      server.close();
    });
    it("should make a standard GET request, like request", done => {
      get("http://127.0.0.1:8127", res => {
        let data = "";
        res.setEncoding("utf8");
        res.on("data", chunk => {
          data += chunk;
        });
        res.on("end", () => {
          expect(data).toBe("Hello World");
          done();
        });
        res.on("error", err => done(err));
      });
    });
  });

  describe("Agent", () => {
    let server;
    let dummyReq;
    let dummyAgent;
    beforeAll(() => {
      dummyAgent = new Agent();
      server = createServer((req, res) => {
        res.writeHead(200, { "Content-Type": "text/plain" });
        res.end("Hello World");
      });
      server.listen(8128, () => {
        // Setup request after server is listening
        dummyReq = request(
          {
            host: "localhost",
            port: 8128,
            agent: dummyAgent,
          },
          res => {},
        );
        dummyReq.on("error", () => {});
      });
    });

    afterAll(() => {
      dummyReq.end();
      server.close();
    });

    it("should be a class", () => {
      expect(Agent instanceof Function).toBe(true);
    });

    it("should have a default maxSockets of Infinity", () => {
      expect(dummyAgent.maxSockets).toBe(Infinity);
    });

    it("should have a keepAlive value", () => {
      expect(dummyAgent.keepAlive).toBe(false);
    });

    it("should noop keepSocketAlive", () => {
      const agent = new Agent({ keepAlive: true });
      expect(agent.keepAlive).toBe(true);
      agent.keepSocketAlive(dummyReq.socket);
    });

    it("should provide globalAgent", () => {
      expect(globalAgent instanceof Agent).toBe(true);
    });
  });
});