aboutsummaryrefslogtreecommitdiff
path: root/test/bun.js/spawn-streaming-stdin.test.ts
blob: 74bf3dbc95c1bd4f449741a8f3d5879acc9620cc (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
import { it, test, expect } from "bun:test";
import { spawn } from "bun";
import { bunExe } from "./bunExe";
import { gcTick } from "gc";
import { closeSync, openSync } from "fs";

const N = 100;
test("spawn can write to stdin multiple chunks", async () => {
  const maxFD = openSync("/dev/null", "w");
  for (let i = 0; i < N; i++) {
    var exited;
    await (async function () {
      const proc = spawn({
        cmd: ["bun-debug", import.meta.dir + "/stdin-repro.js"],
        stdout: "pipe",
        stdin: "pipe",
        stderr: Bun.file("/tmp/out.log"),
        env: {
          BUN_DEBUG_QUIET_LOGS: 1,
        },
      });
      exited = proc.exited;
      var counter = 0;
      var inCounter = 0;
      var chunks = [];
      const prom = (async function () {
        try {
          for await (var chunk of proc.stdout) {
            chunks.push(chunk);
          }
        } catch (e) {
          console.log(e.stack);
          throw e;
        }
      })();

      const prom2 = (async function () {
        while (true) {
          proc.stdin.write("Wrote to stdin!\n");
          inCounter++;
          await new Promise(resolve => setTimeout(resolve, 8));

          if (inCounter === 4) break;
        }
        proc.stdin.end();
      })();

      await Promise.all([prom, prom2]);
      expect(Buffer.concat(chunks).toString().trim()).toBe("Wrote to stdin!\n".repeat(4).trim());
      await proc.exited;
    })();
  }

  closeSync(maxFD);
  const newMaxFD = openSync("/dev/null", "w");
  closeSync(newMaxFD);

  // assert we didn't leak any file descriptors
  expect(newMaxFD).toBe(maxFD);
});