aboutsummaryrefslogtreecommitdiff
path: root/test/bun.js/spawn.test.ts
blob: 0d62d0a5b7205985a7a9fe0f9a0dc9f6eb288010 (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
import { test, expect, it, describe } from "bun:test";
import { readableStreamToText, spawn } from "bun";

describe("spawn", () => {
  const hugeString = "hello".repeat(100000).slice();

  it("stdin can write", async () => {
    const { stdin, stdout } = spawn({
      cmd: ["cat"],
      stdin: "pipe",
      stdout: "pipe",
    });
    await stdin.write(hugeString);
    stdin.end();
    return readableStreamToText(stdout).then((text) => {
      expect(text).toBe(hugeString);
    });
  });

  describe("pipe", () => {
    function huge() {
      return spawn({
        cmd: ["echo", hugeString],
        stdout: "pipe",
        stdin: "pipe",
        stderr: "inherit",
      });
    }

    function helloWorld() {
      return spawn({
        cmd: ["echo", "hello"],
        stdout: "pipe",
        stdin: "pipe",
      });
    }

    const fixtures = [
      [helloWorld, "hello"],
      [huge, hugeString],
    ];

    for (const [callback, fixture] of fixtures) {
      describe(fixture.slice(0, 12), () => {
        describe("should should allow reading stdout", () => {
          it("before exit", async () => {
            const process = callback();
            const output = await readableStreamToText(process.stdout);
            const expected = fixture + "\n";
            expect(output.length).toBe(expected.length);
            expect(output).toBe(expected);

            await process.exited;
          });

          it("before exit (chunked)", async () => {
            const process = callback();
            var output = "";
            var reader = process.stdout.getReader();
            var done = false;
            while (!done) {
              var { value, done } = await reader.read();
              if (value) output += new TextDecoder().decode(value);
            }

            const expected = fixture + "\n";
            expect(output.length).toBe(expected.length);
            expect(output).toBe(expected);

            await process.exited;
          });

          it("after exit", async () => {
            const process = callback();
            await process.stdin.end();

            const output = await readableStreamToText(process.stdout);
            const expected = fixture + "\n";

            expect(output.length).toBe(expected.length);
            expect(output).toBe(expected);

            await process.exited;
          });
        });
      });
    }
  });
});