summaryrefslogtreecommitdiff
path: root/tests/unit_node/child_process_test.ts
blob: f776fa4acd592503e339a0cbcb41b81eca117040 (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
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.

import CP from "node:child_process";
import { Buffer } from "node:buffer";
import {
  assert,
  assertEquals,
  assertExists,
  assertNotStrictEquals,
  assertStrictEquals,
  assertStringIncludes,
  assertThrows,
} from "@std/assert";
import * as path from "@std/path";
import { clearTimeout, setTimeout } from "node:timers";

const { spawn, spawnSync, execFile, execFileSync, ChildProcess } = CP;

function withTimeout<T>(
  timeoutInMS = 10_000,
): ReturnType<typeof Promise.withResolvers<T>> {
  const deferred = Promise.withResolvers<T>();
  const timer = setTimeout(() => {
    deferred.reject("Timeout");
  }, timeoutInMS);
  deferred.promise.then(() => {
    clearTimeout(timer);
  });
  return deferred;
}

// TODO(uki00a): Once Node.js's `parallel/test-child-process-spawn-error.js` works, this test case should be removed.
Deno.test("[node/child_process spawn] The 'error' event is emitted when no binary is found", async () => {
  const deferred = withTimeout<void>();
  const childProcess = spawn("no-such-cmd");
  childProcess.on("error", (_err: Error) => {
    // TODO(@bartlomieju) Assert an error message.
    deferred.resolve();
  });
  await deferred.promise;
});

Deno.test("[node/child_process spawn] The 'exit' event is emitted with an exit code after the child process ends", async () => {
  const deferred = withTimeout<void>();
  const childProcess = spawn(Deno.execPath(), ["--help"], {
    env: { NO_COLOR: "true" },
  });
  try {
    let exitCode = null;
    childProcess.on("exit", (code: number) => {
      deferred.resolve();
      exitCode = code;
    });
    await deferred.promise;
    assertStrictEquals(exitCode, 0);
    assertStrictEquals(childProcess.exitCode, exitCode);
  } finally {
    childProcess.kill();
    childProcess.stdout?.destroy();
    childProcess.stderr?.destroy();
  }
});

Deno.test("[node/child_process disconnect] the method exists", async () => {
  const deferred = withTimeout<void>();
  const childProcess = spawn(Deno.execPath(), ["--help"], {
    env: { NO_COLOR: "true" },
    stdio: ["pipe", "pipe", "pipe", "ipc"],
  });
  try {
    childProcess.disconnect();
    childProcess.on("exit", () => {
      deferred.resolve();
    });
    await deferred.promise;
  } finally {
    childProcess.kill();
    childProcess.stdout?.destroy();
    childProcess.stderr?.destroy();
  }
});

Deno.test({
  name: "[node/child_process spawn] Verify that stdin and stdout work",
  fn: async () => {
    const deferred = withTimeout<void>();
    const childProcess = spawn(Deno.execPath(), ["fmt", "-"], {
      env: { NO_COLOR: "true" },
      stdio: ["pipe", "pipe"],
    });
    try {
      assert(childProcess.stdin, "stdin should be defined");
      assert(childProcess.stdout, "stdout should be defined");
      let data = "";
      childProcess.stdout.on("data", (chunk) => {
        data += chunk;
      });
      childProcess.stdin.write("  console.log('hello')", "utf-8");
      childProcess.stdin.end();
      childProcess.on("close", () => {
        deferred.resolve();
      });
      await deferred.promise;
      assertStrictEquals(data, `console.log("hello");\n`);
    } finally {
      childProcess.kill();
    }
  },
});

Deno.test({
  name: "[node/child_process spawn] stdin and stdout with binary data",
  fn: async () => {
    const deferred = withTimeout<void>();
    const p = path.join(
      path.dirname(path.fromFileUrl(import.meta.url)),
      "./testdata/binary_stdio.js",
    );
    const childProcess = spawn(Deno.execPath(), ["run", p], {
      env: { NO_COLOR: "true" },
      stdio: ["pipe", "pipe"],
    });
    try {
      assert(childProcess.stdin, "stdin should be defined");
      assert(childProcess.stdout, "stdout should be defined");
      let data: Buffer;
      childProcess.stdout.on("data", (chunk) => {
        data = chunk;
      });
      const buffer = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
      childProcess.stdin.write(buffer);
      childProcess.stdin.end();
      childProcess.on("close", () => {
        deferred.resolve();
      });
      await deferred.promise;
      assertEquals(new Uint8Array(data!), buffer);
    } finally {
      childProcess.kill();
    }
  },
});

async function spawnAndGetEnvValue(
  inputValue: string | number | boolean,
): Promise<string> {
  const deferred = withTimeout<string>();
  const env = spawn(
    `"${Deno.execPath()}" eval -p "Deno.env.toObject().BAZ"`,
    {
      env: { BAZ: String(inputValue), NO_COLOR: "true" },
      shell: true,
    },
  );
  try {
    let envOutput = "";

    assert(env.stdout);
    env.on("error", (err: Error) => deferred.reject(err));
    env.stdout.on("data", (data) => {
      envOutput += data;
    });
    env.on("close", () => {
      deferred.resolve(envOutput.trim());
    });
    return await deferred.promise;
  } finally {
    env.kill();
  }
}

Deno.test({
  ignore: Deno.build.os === "windows",
  name:
    "[node/child_process spawn] Verify that environment values can be numbers",
  async fn() {
    const envOutputValue = await spawnAndGetEnvValue(42);
    assertStrictEquals(envOutputValue, "42");
  },
});

Deno.test({
  ignore: Deno.build.os === "windows",
  name:
    "[node/child_process spawn] Verify that environment values can be booleans",
  async fn() {
    const envOutputValue = await spawnAndGetEnvValue(false);
    assertStrictEquals(envOutputValue, "false");
  },
});

/* Start of ported part */
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Ported from Node 15.5.1

// TODO(uki00a): Remove this case once Node's `parallel/test-child-process-spawn-event.js` works.
Deno.test("[child_process spawn] 'spawn' event", async () => {
  const timeout = withTimeout<void>();
  const subprocess = spawn(Deno.execPath(), ["eval", "console.log('ok')"]);

  let didSpawn = false;
  subprocess.on("spawn", function () {
    didSpawn = true;
  });

  function mustNotBeCalled() {
    timeout.reject(new Error("function should not have been called"));
  }

  const promises = [] as Promise<void>[];
  function mustBeCalledAfterSpawn() {
    const deferred = Promise.withResolvers<void>();
    promises.push(deferred.promise);
    return () => {
      if (didSpawn) {
        deferred.resolve();
      } else {
        deferred.reject(
          new Error("function should be called after the 'spawn' event"),
        );
      }
    };
  }

  subprocess.on("error", mustNotBeCalled);
  subprocess.stdout!.on("data", mustBeCalledAfterSpawn());
  subprocess.stdout!.on("end", mustBeCalledAfterSpawn());
  subprocess.stdout!.on("close", mustBeCalledAfterSpawn());
  subprocess.stderr!.on("data", mustNotBeCalled);
  subprocess.stderr!.on("end", mustBeCalledAfterSpawn());
  subprocess.stderr!.on("close", mustBeCalledAfterSpawn());
  subprocess.on("exit", mustBeCalledAfterSpawn());
  subprocess.on("close", mustBeCalledAfterSpawn());

  try {
    await Promise.race([Promise.all(promises), timeout.promise]);
    timeout.resolve();
  } finally {
    subprocess.kill();
  }
});

// TODO(uki00a): Remove this case once Node's `parallel/test-child-process-spawn-shell.js` works.
Deno.test("[child_process spawn] Verify that a shell is executed", async () => {
  const deferred = withTimeout<void>();
  const doesNotExist = spawn("does-not-exist", { shell: true });
  try {
    assertNotStrictEquals(doesNotExist.spawnfile, "does-not-exist");
    doesNotExist.on("error", () => {
      deferred.reject("The 'error' event must not be emitted.");
    });
    doesNotExist.on("exit", (code: number, signal: null) => {
      assertStrictEquals(signal, null);

      if (Deno.build.os === "windows") {
        assertStrictEquals(code, 1); // Exit code of cmd.exe
      } else {
        assertStrictEquals(code, 127); // Exit code of /bin/sh });
      }

      deferred.resolve();
    });
    await deferred.promise;
  } finally {
    doesNotExist.kill();
    doesNotExist.stdout?.destroy();
    doesNotExist.stderr?.destroy();
  }
});

// TODO(uki00a): Remove this case once Node's `parallel/test-child-process-spawn-shell.js` works.
Deno.test({
  ignore: Deno.build.os === "windows",
  name: "[node/child_process spawn] Verify that passing arguments works",
  async fn() {
    const deferred = withTimeout<void>();
    const echo = spawn("echo", ["foo"], {
      shell: true,
    });
    let echoOutput = "";

    try {
      assertStrictEquals(
        echo.spawnargs[echo.spawnargs.length - 1].replace(/"/g, ""),
        "echo foo",
      );
      assert(echo.stdout);
      echo.stdout.on("data", (data) => {
        echoOutput += data;
      });
      echo.on("close", () => {
        assertStrictEquals(echoOutput.trim(), "foo");
        deferred.resolve();
      });
      await deferred.promise;
    } finally {
      echo.kill();
    }
  },
});

// TODO(uki00a): Remove this case once Node's `parallel/test-child-process-spawn-shell.js` works.
Deno.test({
  ignore: Deno.build.os === "windows",
  name: "[node/child_process spawn] Verity that shell features can be used",
  async fn() {
    const deferred = withTimeout<void>();
    const cmd = "echo bar | cat";
    const command = spawn(cmd, {
      shell: true,
    });
    try {
      let commandOutput = "";

      assert(command.stdout);
      command.stdout.on("data", (data) => {
        commandOutput += data;
      });

      command.on("close", () => {
        assertStrictEquals(commandOutput.trim(), "bar");
        deferred.resolve();
      });

      await deferred.promise;
    } finally {
      command.kill();
    }
  },
});

// TODO(uki00a): Remove this case once Node's `parallel/test-child-process-spawn-shell.js` works.
Deno.test({
  ignore: Deno.build.os === "windows",
  name:
    "[node/child_process spawn] Verity that environment is properly inherited",
  async fn() {
    const deferred = withTimeout<void>();
    const env = spawn(
      `"${Deno.execPath()}" eval -p "Deno.env.toObject().BAZ"`,
      {
        env: { BAZ: "buzz", NO_COLOR: "true" },
        shell: true,
      },
    );
    try {
      let envOutput = "";

      assert(env.stdout);
      env.on("error", (err: Error) => deferred.reject(err));
      env.stdout.on("data", (data) => {
        envOutput += data;
      });
      env.on("close", () => {
        assertStrictEquals(envOutput.trim(), "buzz");
        deferred.resolve();
      });
      await deferred.promise;
    } finally {
      env.kill();
    }
  },
});
/* End of ported part */

Deno.test({
  name: "[node/child_process execFile] Get stdout as a string",
  async fn() {
    let child: unknown;
    const script = path.join(
      path.dirname(path.fromFileUrl(import.meta.url)),
      "./testdata/exec_file_text_output.js",
    );
    const promise = new Promise<string | null>((resolve, reject) => {
      child = execFile(Deno.execPath(), ["run", script], (err, stdout) => {
        if (err) reject(err);
        else if (stdout) resolve(stdout as string);
        else resolve(null);
      });
    });
    try {
      const stdout = await promise;
      assertEquals(stdout, "Hello World!\n");
    } finally {
      if (child instanceof ChildProcess) {
        child.kill();
      }
    }
  },
});

Deno.test({
  name: "[node/child_process execFile] Get stdout as a buffer",
  async fn() {
    let child: unknown;
    const script = path.join(
      path.dirname(path.fromFileUrl(import.meta.url)),
      "./testdata/exec_file_text_output.js",
    );
    const promise = new Promise<Buffer | null>((resolve, reject) => {
      child = execFile(
        Deno.execPath(),
        ["run", script],
        { encoding: "buffer" },
        (err, stdout) => {
          if (err) reject(err);
          else if (stdout) resolve(stdout as Buffer);
          else resolve(null);
        },
      );
    });
    try {
      const stdout = await promise;
      assert(Buffer.isBuffer(stdout));
      assertEquals(stdout.toString("utf8"), "Hello World!\n");
    } finally {
      if (child instanceof ChildProcess) {
        child.kill();
      }
    }
  },
});

Deno.test({
  name: "[node/child_process execFile] Get stderr",
  async fn() {
    let child: unknown;
    const script = path.join(
      path.dirname(path.fromFileUrl(import.meta.url)),
      "./testdata/exec_file_text_error.js",
    );
    const promise = new Promise<
      { err: Error | null; stderr?: string | Buffer }
    >((resolve) => {
      child = execFile(Deno.execPath(), ["run", script], (err, _, stderr) => {
        resolve({ err, stderr });
      });
    });
    try {
      const { err, stderr } = await promise;
      if (child instanceof ChildProcess) {
        assertEquals(child.exitCode, 1);
        assertEquals(stderr, "yikes!\n");
      } else {
        throw err;
      }
    } finally {
      if (child instanceof ChildProcess) {
        child.kill();
      }
    }
  },
});

Deno.test({
  name: "[node/child_process execFile] Exceed given maxBuffer limit",
  async fn() {
    let child: unknown;
    const script = path.join(
      path.dirname(path.fromFileUrl(import.meta.url)),
      "./testdata/exec_file_text_error.js",
    );
    const promise = new Promise<
      { err: Error | null; stderr?: string | Buffer }
    >((resolve) => {
      child = execFile(Deno.execPath(), ["run", script], {
        encoding: "buffer",
        maxBuffer: 3,
      }, (err, _, stderr) => {
        resolve({ err, stderr });
      });
    });
    try {
      const { err, stderr } = await promise;
      if (child instanceof ChildProcess) {
        assert(err);
        assertEquals(
          // deno-lint-ignore no-explicit-any
          (err as any).code,
          "ERR_CHILD_PROCESS_STDIO_MAXBUFFER",
        );
        assertEquals(err.message, "stderr maxBuffer length exceeded");
        assertEquals((stderr as Buffer).toString("utf8"), "yik");
      } else {
        throw err;
      }
    } finally {
      if (child instanceof ChildProcess) {
        child.kill();
      }
    }
  },
});

Deno.test({
  name: "[node/child_process] ChildProcess.kill()",
  async fn() {
    const script = path.join(
      path.dirname(path.fromFileUrl(import.meta.url)),
      "./testdata/infinite_loop.js",
    );
    const childProcess = spawn(Deno.execPath(), ["run", script]);
    const p = withTimeout<void>();
    const pStdout = withTimeout<void>();
    const pStderr = withTimeout<void>();
    childProcess.on("exit", () => p.resolve());
    childProcess.stdout.on("close", () => pStdout.resolve());
    childProcess.stderr.on("close", () => pStderr.resolve());
    childProcess.kill("SIGKILL");
    await p.promise;
    await pStdout.promise;
    await pStderr.promise;
    assert(childProcess.killed);
    assertEquals(childProcess.signalCode, "SIGKILL");
    assertExists(childProcess.exitCode);
  },
});

Deno.test({
  ignore: true,
  name: "[node/child_process] ChildProcess.unref()",
  async fn() {
    const script = path.join(
      path.dirname(path.fromFileUrl(import.meta.url)),
      "testdata",
      "child_process_unref.js",
    );
    const childProcess = spawn(Deno.execPath(), [
      "run",
      "-A",
      script,
    ]);
    const deferred = Promise.withResolvers<void>();
    childProcess.on("exit", () => deferred.resolve());
    await deferred.promise;
  },
});

Deno.test({
  ignore: true,
  name: "[node/child_process] child_process.fork",
  async fn() {
    const testdataDir = path.join(
      path.dirname(path.fromFileUrl(import.meta.url)),
      "testdata",
    );
    const script = path.join(
      testdataDir,
      "node_modules",
      "foo",
      "index.js",
    );
    const p = Promise.withResolvers<void>();
    const cp = CP.fork(script, [], { cwd: testdataDir, stdio: "pipe" });
    let output = "";
    cp.on("close", () => p.resolve());
    cp.stdout?.on("data", (data) => {
      output += data;
    });
    await p.promise;
    assertEquals(output, "foo\ntrue\ntrue\ntrue\n");
  },
});

Deno.test("[node/child_process execFileSync] 'inherit' stdout and stderr", () => {
  execFileSync(Deno.execPath(), ["--help"], { stdio: "inherit" });
});

Deno.test(
  "[node/child_process spawn] supports windowsVerbatimArguments option",
  { ignore: Deno.build.os !== "windows" },
  async () => {
    const cmdFinished = Promise.withResolvers<void>();
    let output = "";
    const cp = spawn("cmd", ["/d", "/s", "/c", '"deno ^"--version^""'], {
      stdio: "pipe",
      windowsVerbatimArguments: true,
    });
    cp.on("close", () => cmdFinished.resolve());
    cp.stdout?.on("data", (data) => {
      output += data;
    });
    await cmdFinished.promise;
    assertStringIncludes(output, "deno");
    assertStringIncludes(output, "v8");
    assertStringIncludes(output, "typescript");
  },
);

Deno.test(
  "[node/child_process spawn] supports stdio array option",
  async () => {
    const cmdFinished = Promise.withResolvers<void>();
    let output = "";
    const script = path.join(
      path.dirname(path.fromFileUrl(import.meta.url)),
      "testdata",
      "child_process_stdio.js",
    );
    const cp = spawn(Deno.execPath(), ["run", "-A", script]);
    cp.stdout?.on("data", (data) => {
      output += data;
    });
    cp.on("close", () => cmdFinished.resolve());
    await cmdFinished.promise;

    assertStringIncludes(output, "foo");
    assertStringIncludes(output, "close");
  },
);

Deno.test(
  "[node/child_process spawn] supports stdio [0, 1, 2] option",
  async () => {
    const cmdFinished = Promise.withResolvers<void>();
    let output = "";
    const script = path.join(
      path.dirname(path.fromFileUrl(import.meta.url)),
      "testdata",
      "child_process_stdio_012.js",
    );
    const cp = spawn(Deno.execPath(), ["run", "-A", script]);
    cp.stdout?.on("data", (data) => {
      output += data;
    });
    cp.on("close", () => cmdFinished.resolve());
    await cmdFinished.promise;

    assertStringIncludes(output, "foo");
    assertStringIncludes(output, "close");
  },
);

Deno.test({
  name: "[node/child_process spawn] supports SIGIOT signal",
  ignore: Deno.build.os === "windows",
  async fn() {
    // Note: attempting to kill Deno with SIGABRT causes the process to zombify on certain OSX builds
    // eg: 22.5.0 Darwin Kernel Version 22.5.0: Mon Apr 24 20:53:19 PDT 2023; root:xnu-8796.121.2~5/RELEASE_ARM64_T6020 arm64
    // M2 Pro running Ventura 13.4

    // Spawn an infinite cat
    const cp = spawn("cat", ["-"]);
    const p = withTimeout<void>();
    const pStdout = withTimeout<void>();
    const pStderr = withTimeout<void>();
    cp.on("exit", () => p.resolve());
    cp.stdout.on("close", () => pStdout.resolve());
    cp.stderr.on("close", () => pStderr.resolve());
    cp.kill("SIGIOT");
    await p.promise;
    await pStdout.promise;
    await pStderr.promise;
    assert(cp.killed);
    assertEquals(cp.signalCode, "SIGIOT");
  },
});

// Regression test for https://github.com/denoland/deno/issues/20373
Deno.test(async function undefinedValueInEnvVar() {
  const deferred = withTimeout<string>();
  const env = spawn(
    `"${Deno.execPath()}" eval -p "Deno.env.toObject().BAZ"`,
    {
      env: {
        BAZ: "BAZ",
        NO_COLOR: "true",
        UNDEFINED_ENV: undefined,
        // deno-lint-ignore no-explicit-any
        NULL_ENV: null as any,
      },
      shell: true,
    },
  );
  try {
    let envOutput = "";

    assert(env.stdout);
    env.on("error", (err: Error) => deferred.reject(err));
    env.stdout.on("data", (data) => {
      envOutput += data;
    });
    env.on("close", () => {
      deferred.resolve(envOutput.trim());
    });
    await deferred.promise;
  } finally {
    env.kill();
  }
  const value = await deferred.promise;
  assertEquals(value, "BAZ");
});

// Regression test for https://github.com/denoland/deno/issues/20373
Deno.test(function spawnSyncUndefinedValueInEnvVar() {
  const ret = spawnSync(
    `"${Deno.execPath()}" eval -p "Deno.env.toObject().BAZ"`,
    {
      env: {
        BAZ: "BAZ",
        NO_COLOR: "true",
        UNDEFINED_ENV: undefined,
        // deno-lint-ignore no-explicit-any
        NULL_ENV: null as any,
      },
      shell: true,
    },
  );

  assertEquals(ret.status, 0);
  assertEquals(ret.stdout.toString("utf-8").trim(), "BAZ");
});

Deno.test(function spawnSyncStdioUndefined() {
  const ret = spawnSync(
    `"${Deno.execPath()}" eval "console.log('hello');console.error('world')"`,
    {
      stdio: [undefined, undefined, undefined],
      shell: true,
    },
  );

  assertEquals(ret.status, 0);
  assertEquals(ret.stdout.toString("utf-8").trim(), "hello");
  assertEquals(ret.stderr.toString("utf-8").trim(), "world");
});

Deno.test(function spawnSyncExitNonZero() {
  const ret = spawnSync(
    `"${Deno.execPath()}" eval "Deno.exit(22)"`,
    { shell: true },
  );

  assertEquals(ret.status, 22);
});

// https://github.com/denoland/deno/issues/21630
Deno.test(async function forkIpcKillDoesNotHang() {
  const testdataDir = path.join(
    path.dirname(path.fromFileUrl(import.meta.url)),
    "testdata",
  );
  const script = path.join(
    testdataDir,
    "node_modules",
    "foo",
    "index.js",
  );
  const p = Promise.withResolvers<void>();
  const cp = CP.fork(script, [], {
    cwd: testdataDir,
    stdio: ["inherit", "inherit", "inherit", "ipc"],
  });
  cp.on("close", () => p.resolve());
  cp.kill();

  await p.promise;
});

Deno.test(async function stripForkEnableSourceMaps() {
  const testdataDir = path.join(
    path.dirname(path.fromFileUrl(import.meta.url)),
    "testdata",
  );
  const script = path.join(
    testdataDir,
    "node_modules",
    "foo",
    "check_argv.js",
  );
  const p = Promise.withResolvers<void>();
  const cp = CP.fork(script, [], {
    cwd: testdataDir,
    stdio: "pipe",
    execArgv: ["--enable-source-maps"],
  });
  let output = "";
  cp.on("close", () => p.resolve());
  cp.stdout?.on("data", (data) => {
    output += data;
    cp.kill();
  });
  await p.promise;
  assertEquals(output, "2\n");
});

Deno.test(async function execFileWithUndefinedTimeout() {
  const { promise, resolve, reject } = Promise.withResolvers<void>();
  CP.execFile(
    "git",
    ["--version"],
    { timeout: undefined, encoding: "utf8" },
    (err) => {
      if (err) {
        reject(err);
        return;
      }
      resolve();
    },
  );
  await promise;
});

Deno.test(async function spawnCommandNotFoundErrno() {
  const { promise, resolve } = Promise.withResolvers<void>();
  const cp = CP.spawn("no-such-command");
  cp.on("error", (err) => {
    const errno = Deno.build.os === "windows" ? -4058 : -2;
    // @ts-ignore: errno missing from typings
    assertEquals(err.errno, errno);
    resolve();
  });
  await promise;
});

// https://github.com/denoland/deno/issues/23045
Deno.test(function spawnCommandNullStdioArray() {
  const ret = spawnSync(
    `"${Deno.execPath()}" eval "console.log('hello');console.error('world')"`,
    {
      stdio: [null, null, null],
      shell: true,
    },
  );

  assertEquals(ret.status, 0);
});

Deno.test(
  function stdinInherit() {
    const script = `
      function timeoutPromise(promise, timeout) {
        return new Promise((resolve, reject) => {
          const timeoutId = setTimeout(() => {
            Deno.exit(69);
          }, timeout);
          promise.then((value) => {
            clearTimeout(timeoutId);
            resolve(value);
          }, (reason) => {
            clearTimeout(timeoutId);
            reject(reason);
          });
        });
      }

      await timeoutPromise(Deno.stdin.read(new Uint8Array(1)), 100)
    `;

    const output = spawnSync(Deno.execPath(), ["eval", script], {
      stdio: "inherit",
    });

    // We want to timeout to occur because the stdin isn't 'null'
    assertEquals(output.status, 69);
    assertEquals(output.stdout, null);
    assertEquals(output.stderr, null);
  },
);

Deno.test(
  async function ipcSerialization() {
    const timeout = withTimeout<void>();
    const script = `
      if (typeof process.send !== "function") {
        console.error("process.send is not a function");
        process.exit(1);
      }

      class BigIntWrapper {
        constructor(value) {
          this.value = value;
        }
        toJSON() {
          return this.value.toString();
        }
      }

      const makeSab = (arr) => {
        const sab = new SharedArrayBuffer(arr.length);
        const buf = new Uint8Array(sab);
        for (let i = 0; i < arr.length; i++) {
          buf[i] = arr[i];
        }
        return buf;
      };


      const inputs = [
        "foo",
        {
          foo: "bar",
        },
        42,
        true,
        null,
        new Uint8Array([1, 2, 3]),
        {
          foo: new Uint8Array([1, 2, 3]),
          bar: makeSab([4, 5, 6]),
        },
        [1, { foo: 2 }, [3, 4]],
        new BigIntWrapper(42n),
      ];
      for (const input of inputs) {
        process.send(input);
      }
    `;
    const file = await Deno.makeTempFile();
    await Deno.writeTextFile(file, script);
    const child = CP.fork(file, [], {
      stdio: ["inherit", "inherit", "inherit", "ipc"],
    });
    const expect = [
      "foo",
      {
        foo: "bar",
      },
      42,
      true,
      null,
      [1, 2, 3],
      {
        foo: [1, 2, 3],
        bar: [4, 5, 6],
      },
      [1, { foo: 2 }, [3, 4]],
      "42",
    ];
    let i = 0;

    child.on("message", (message) => {
      assertEquals(message, expect[i]);
      i++;
    });
    child.on("close", () => timeout.resolve());
    await timeout.promise;
    assertEquals(i, expect.length);
  },
);

Deno.test(async function childProcessExitsGracefully() {
  const testdataDir = path.join(
    path.dirname(path.fromFileUrl(import.meta.url)),
    "testdata",
  );
  const script = path.join(
    testdataDir,
    "node_modules",
    "foo",
    "index.js",
  );
  const p = Promise.withResolvers<void>();
  const cp = CP.fork(script, [], {
    cwd: testdataDir,
    stdio: ["inherit", "inherit", "inherit", "ipc"],
  });
  cp.on("close", () => p.resolve());

  await p.promise;
});

Deno.test(async function killMultipleTimesNoError() {
  const loop = `
    while (true) {
      await new Promise((resolve) => setTimeout(resolve, 10000));
    }
  `;

  const timeout = withTimeout<void>();
  const file = await Deno.makeTempFile();
  await Deno.writeTextFile(file, loop);
  const child = CP.fork(file, [], {
    stdio: ["inherit", "inherit", "inherit", "ipc"],
  });
  child.on("close", () => {
    timeout.resolve();
  });
  child.kill();
  child.kill();

  // explicitly calling disconnect after kill should throw
  assertThrows(() => child.disconnect());

  await timeout.promise;
});

// Make sure that you receive messages sent before a "message" event listener is set up
Deno.test(async function bufferMessagesIfNoListener() {
  const code = `
    process.on("message", (_) => {
      process.channel.unref();
    });
    process.send("hello");
    process.send("world");
    console.error("sent messages");
  `;
  const file = await Deno.makeTempFile();
  await Deno.writeTextFile(file, code);
  const timeout = withTimeout<void>();
  const child = CP.fork(file, [], {
    stdio: ["inherit", "inherit", "pipe", "ipc"],
  });

  let got = 0;
  child.on("message", (message) => {
    if (got++ === 0) {
      assertEquals(message, "hello");
    } else {
      assertEquals(message, "world");
    }
  });
  child.on("close", () => {
    timeout.resolve();
  });
  let stderr = "";
  child.stderr?.on("data", (data) => {
    stderr += data;
    if (stderr.includes("sent messages")) {
      // now that we've set up the listeners, and the child
      // has sent the messages, we can let it exit
      child.send("ready");
    }
  });
  await timeout.promise;
  assertEquals(got, 2);
});

Deno.test(async function sendAfterClosedThrows() {
  const code = ``;
  const file = await Deno.makeTempFile();
  await Deno.writeTextFile(file, code);
  const timeout = withTimeout<void>();
  const child = CP.fork(file, [], {
    stdio: ["inherit", "inherit", "inherit", "ipc"],
  });
  child.on("error", (err) => {
    assert("code" in err);
    assertEquals(err.code, "ERR_IPC_CHANNEL_CLOSED");
    timeout.resolve();
  });
  child.on("close", () => {
    child.send("ready");
  });

  await timeout.promise;
});