forked from dsherret/dax
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.test.ts
2247 lines (2024 loc) · 67.8 KB
/
mod.test.ts
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
import { assert, assertEquals, assertMatch, assertRejects, assertStringIncludes, assertThrows } from "@std/assert";
import * as colors from "@std/fmt/colors";
import { Buffer } from "@std/io/buffer";
import { readAll } from "@std/io/read-all";
import { toWritableStream } from "@std/io/to-writable-stream";
import * as path from "@std/path";
import { readerFromStreamReader } from "@std/streams/reader-from-stream-reader";
import { isNode } from "which_runtime";
import $, {
build$,
CommandBuilder,
type CommandContext,
type CommandHandler,
KillSignal,
KillSignalController,
Path,
PathRef,
} from "./mod.ts";
import { setNotTtyForTesting } from "./src/console/utils.ts";
import { usingTempDir, withTempDir } from "./src/with_temp_dir.ts";
// Deno will not be a tty because it captures the pipes, but Node
// will be, so manually say that we're not a tty for testing so
// the tests behave somewhat similarly in Node.js
setNotTtyForTesting();
Deno.test("should get stdout when piped", async () => {
const output = await $`echo 5`.stdout("piped");
assertEquals(output.code, 0);
assertEquals(output.stdout, "5\n");
});
Deno.test("should escape arguments", async () => {
const text = await $`echo ${"testing 'this $TEST \`out"}`.text();
assertEquals(text, "testing 'this $TEST `out");
});
Deno.test("should not get stdout when inherited (default)", async () => {
const output = await $`echo "should output"`;
assertEquals(output.code, 0);
assertThrows(() => output.stdout, Error, `Stdout was not piped (was inherit).`);
});
Deno.test("should not get stdout when null", async () => {
const output = await $`echo 5`.stdout("null");
assertEquals(output.code, 0);
assertThrows(() => output.stdout, Error, `Stdout was not piped (was null).`);
});
Deno.test("should capture stdout when piped", async () => {
const output = await $`deno eval 'console.log(5);'`.stdout("piped");
assertEquals(output.code, 0);
assertEquals(output.stdout, "5\n");
});
Deno.test("should capture stdout when inherited and piped", async () => {
const output = await $`deno eval 'console.log(5);'`.stdout("inheritPiped");
assertEquals(output.code, 0);
assertEquals(output.stdout, "5\n");
});
Deno.test("should not get stdout when set to writer", async () => {
const buffer = new Buffer();
const output = await $`echo 5`.stdout(buffer);
assertEquals(output.code, 0);
assertEquals(new TextDecoder().decode(buffer.bytes()), "5\n");
assertThrows(() => output.stdout, Error, `Stdout was streamed to another source and is no longer available.`);
});
Deno.test("should not get stderr when inherited only (default)", async () => {
const output = await $`deno eval 'console.error("should output");'`;
assertEquals(output.code, 0);
assertThrows(
() => output.stderr,
Error,
`Stderr was not piped (was inherit). Call .stderr("piped") or .stderr("inheritPiped") when building the command.`,
);
});
Deno.test("should not get stderr when null", async () => {
const output = await $`deno eval 'console.error(5);'`.stderr("null");
assertEquals(output.code, 0);
assertThrows(
() => output.stderr,
Error,
`Stderr was not piped (was null). Call .stderr("piped") or .stderr("inheritPiped") when building the command.`,
);
});
Deno.test("should capture stderr when piped", async () => {
const output = await $`deno eval 'console.error(5);'`
.env("NO_COLOR", "1") // deno uses colors when only stderr is piped
.stderr("piped");
assertEquals(output.code, 0);
assertEquals(output.stderr, "5\n");
});
Deno.test("should capture stderr when inherited and piped", async () => {
const output = await $`deno eval -q 'console.error(5);'`
.env("NO_COLOR", "1")
.stderr("inheritPiped");
assertEquals(output.code, 0);
assertEquals(output.stderr, "5\n");
});
Deno.test("should not get stderr when set to writer", async () => {
const buffer = new Buffer();
const output = await $`deno eval 'console.error(5); console.log(1);'`
.env("NO_COLOR", "1")
.stderr(buffer);
assertEquals(output.code, 0);
assertEquals(new TextDecoder().decode(buffer.bytes()), "5\n");
assertThrows(
() => output.stderr,
Error,
`Stderr was streamed to another source and is no longer available.`,
);
});
Deno.test("should get combined stdout and stderr when specified", async () => {
const output = await $`echo 1 ; sleep 0.5 ; deno eval -q 'console.error(2);'`.captureCombined();
assertEquals(output.code, 0);
assertEquals(output.combined, "1\n2\n");
});
Deno.test("should not get combined stdout and stderr when not calling combined output", async () => {
const output = await $`deno eval -q 'console.error("should output");'`.stdout("piped").stderr("piped");
assertEquals(output.code, 0);
assertThrows(
() => output.combined,
Error,
`Stdout and stderr were not combined. Call .captureCombined() when building the command.`,
);
});
Deno.test("should error setting stdout after getting combined output", () => {
for (const value of ["null", "inherit"] as const) {
assertThrows(
() => {
$``.captureCombined(true).stdout(value);
},
Error,
"Cannot set stdout's kind to anything but 'piped' or 'inheritPiped' when combined is true.",
);
assertThrows(
() => {
$``.captureCombined(true).stderr(value);
},
Error,
"Cannot set stderr's kind to anything but 'piped' or 'inheritPiped' when combined is true.",
);
}
});
Deno.test("should get output as bytes", async () => {
{
const output = await $`echo 5 && deno eval 'console.error(1);'`.bytes();
assertEquals(new TextDecoder().decode(output), "5\n");
}
{
const output = await $`echo 5 && deno eval 'console.error(1);'`.bytes("combined");
assertEquals(new TextDecoder().decode(output), "5\n1\n");
}
{
const output = await $`echo 5 && deno eval 'console.error(1);'`.env("NOCOLOR", "1")
.bytes("stderr");
assertEquals(new TextDecoder().decode(output), "1\n");
}
});
Deno.test("should throw when exit code is non-zero", async () => {
await assertRejects(
async () => {
await $`deno eval 'Deno.exit(1);'`;
},
Error,
"Exited with code: 1",
);
await assertRejects(
async () => {
await $`deno eval 'Deno.exit(2);'`;
},
Error,
"Exited with code: 2",
);
await assertRejects(
async () => {
await $`exit 3 && echo 1 && echo 2`;
},
Error,
"Exited with code: 3",
);
// regression test for previous bug
await assertRejects(
async () => {
await $`echo 1 && echo 2 && exit 3`;
},
Error,
"Exited with code: 3",
);
});
Deno.test("should error in the shell when the command can't be found", async () => {
const output = await $`nonexistentcommanddaxtest`.noThrow().stderr("piped");
assertEquals(output.code, 127);
assertEquals(output.stderr, "dax: nonexistentcommanddaxtest: command not found\n");
});
Deno.test("throws when providing an object that doesn't override toString", async () => {
{
const obj1 = {};
assertThrows(
() => $`echo ${obj1}`,
Error,
"Failed resolving expression in command. Provided object does not override `toString()`.",
);
}
{
const obj2 = {
toString() {
return "1";
},
};
const result = await $`echo ${obj2}`.text();
assertEquals(result, "1");
}
class Test {
toString() {
return "1";
}
}
{
const result = await $`echo ${new Test()}`.text();
assertEquals(result, "1");
}
});
Deno.test("should change the cwd, but only in the shell", async () => {
const output = await $`cd src ; deno eval 'console.log(Deno.cwd());'`.stdout("piped");
const standardizedOutput = output.stdout.trim().replace(/\\/g, "/");
assertEquals(standardizedOutput.endsWith("src"), true, standardizedOutput);
});
Deno.test("allow setting env", async () => {
const output = await $`echo $test`.env("test", "123").text();
assertEquals(output, "123");
});
Deno.test("allow setting multiple env", async () => {
const output = await $`echo $test$other`.env({
test: "123",
other: "456",
}).text();
assertEquals(output, "123456");
});
Deno.test("set var for command", async () => {
const output = await $`test=123 echo $test ; echo $test`
.env("test", "456")
.text();
assertEquals(output, "123\n456");
});
Deno.test("variable substitution", async () => {
const output = await $`deno eval "console.log($TEST);"`.env("TEST", "123").text();
assertEquals(output.trim(), "123");
});
Deno.test("stdoutJson", async () => {
const output = await $`deno eval "console.log(JSON.stringify({ test: 5 }));"`.stdout("piped");
assertEquals(output.stdoutJson, { test: 5 });
assertEquals(output.stdoutJson === output.stdoutJson, true); // should be memoized
});
Deno.test("CommandBuilder#json()", async () => {
const output = await $`deno eval "console.log(JSON.stringify({ test: 5 }));"`.json();
assertEquals(output, { test: 5 });
});
Deno.test("CommandBuilder#json('stderr')", async () => {
const output = await $`deno eval "console.error(JSON.stringify({ test: 5 }));"`.json("stderr");
assertEquals(output, { test: 5 });
});
Deno.test("stderrJson", async () => {
const output = await $`deno eval "console.error(JSON.stringify({ test: 5 }));"`.stderr("piped");
assertEquals(output.stderrJson, { test: 5 });
assertEquals(output.stderrJson === output.stderrJson, true); // should be memoized
});
Deno.test("stderr text", async () => {
const result = await $`deno eval "console.error(1)"`.env("NO_COLOR", "1").text("stderr");
assertEquals(result, "1");
});
Deno.test("should handle interpolation", async () => {
const output = await $`deno eval 'console.log(${5});'`.stdout("piped");
assertEquals(output.code, 0);
assertEquals(output.stdout, "5\n");
});
Deno.test("should handle interpolation beside args", async () => {
const value = "a/b";
const text = await $`echo ${value}/c`.text();
assertEquals(text, "a/b/c");
});
Deno.test("should handle providing array of arguments", async () => {
const args = [1, "2", "test test"];
const text = await $`deno eval 'console.log(Deno.args)' ${args}`.text();
assertEquals(text, `[ "1", "2", "test test" ]`);
});
Deno.test("raw should handle providing array of arguments", async () => {
const args = [1, "2", "test test"];
const text = await $.raw`deno eval 'console.log(Deno.args)' ${args}`.text();
assertEquals(text, `[ "1", "2", "test", "test" ]`);
});
Deno.test("raw should handle text provided", async () => {
const text = await $.raw`deno eval 'console.log(Deno.args)' ${"testing this out"}`.text();
assertEquals(text, `[ "testing", "this", "out" ]`);
});
Deno.test("raw should handle command result", async () => {
const result = await $`echo '1 2 3'`.stdout("piped");
const text = await $.raw`deno eval 'console.log(Deno.args)' ${result}`.text();
assertEquals(text, `[ "1", "2", "3" ]`);
});
Deno.test("command builder should build", async () => {
const commandBuilder = new CommandBuilder()
.env("TEST", "123");
{
const local$ = $.build$({ commandBuilder });
// after creating a $, the environment should be set in stone, so changing
// this environment variable should have no effect here. Additionally,
// command builders are immutable and return a new builder each time
commandBuilder.env("TEST", "456");
const output = await local$`deno eval 'console.log(Deno.env.get("TEST"));'`.stdout("piped");
assertEquals(output.code, 0);
assertEquals(output.stdout, "123\n");
}
{
// this one additionally won't be affected because command builders are immutable
const local$ = $.build$({ commandBuilder });
const output = await local$`deno eval 'console.log(Deno.env.get("TEST"));'`.stdout("piped");
assertEquals(output.code, 0);
assertEquals(output.stdout, "123\n");
}
});
Deno.test("build with extras", () => {
const local$ = build$({
extras: {
add(a: number, b: number) {
return a + b;
},
},
});
assertEquals(local$.add(1, 2), 3);
const local$2 = local$.build$({
extras: {
subtract(a: number, b: number) {
return a - b;
},
},
});
assertEquals(local$2.add(1, 2), 3);
assertEquals(local$2.subtract(1, 2), -1);
const local$3 = local$2.build$({
extras: {
add(a: string, b: string) {
return a + b;
},
recursive(a: number, times = 0): number {
if (a === 0) {
return times;
} else {
return local$3.recursive(a - 1, times + 1);
}
},
},
});
const result = local$3.add("test", "other");
assertEquals(result, "testother");
// @ts-expect-error should error for non-string
const _assertStringFail: number = result;
const _assertStringPass: string = result;
const _noExecute = () => {
// @ts-expect-error should overwrite previous declaration
local$3.add(2, 2);
build$({
extras: {
// @ts-expect-error only supports functions at the moment
prop: 5,
},
});
};
assertEquals(local$3.recursive(3), 3);
});
Deno.test("build with extras overriding the defaults", () => {
const local$ = build$({
extras: {
escapeArg(a: number, b: number) {
return a + b;
},
},
});
// @ts-expect-error should overwrite previous declaration
local$.escapeArg("test");
$.escapeArg("test");
assertEquals(local$.escapeArg(1, 2), 3);
});
Deno.test("should handle boolean list 'or'", async () => {
{
const output = await $`deno eval 'Deno.exit(1)' || deno eval 'console.log(5)'`.text();
assertEquals(output, "5");
}
{
const output = await $`deno eval 'Deno.exit(1)' || deno eval 'Deno.exit(2)' || deno eval 'Deno.exit(3)'`
.noThrow()
.stdout("piped");
assertEquals(output.stdout, "");
assertEquals(output.code, 3);
}
});
Deno.test("should handle boolean list 'and'", async () => {
{
const output = await $`deno eval 'Deno.exit(5)' && echo 2`.noThrow().stdout("piped");
assertEquals(output.code, 5);
assertEquals(output.stdout, "");
}
{
const output = await $`deno eval 'Deno.exit(0)' && echo 5 && echo 6`.stdout("piped");
assertEquals(output.code, 0);
assertEquals(output.stdout.trim(), "5\n6");
}
});
Deno.test("should support custom command handlers", async () => {
const builder = new CommandBuilder()
.registerCommand("zardoz-speaks", async (context) => {
if (context.args.length != 1) {
return context.error("zardoz-speaks: expected 1 argument");
}
await context.stdout.writeLine(`zardoz speaks to ${context.args[0]}`);
return {
code: 0,
};
})
.registerCommands({
"true": () => Promise.resolve({ code: 0 }),
"false": () => Promise.resolve({ code: 1 }),
}).stderr("piped").stdout("piped");
{
const result = await builder.command("zardoz-speaks").noThrow();
assertEquals(result.code, 1);
assertEquals(result.stderr, "zardoz-speaks: expected 1 argument\n");
}
{
const result = await builder.command("zardoz-speaks to you").noThrow();
assertEquals(result.code, 1);
assertEquals(result.stderr, "zardoz-speaks: expected 1 argument\n");
}
{
const result = await builder.command("zardoz-speaks you").noThrow();
assertEquals(result.code, 0);
assertEquals(result.stdout, "zardoz speaks to you\n");
}
{
const result = await builder.command("true && echo yup").noThrow();
assertEquals(result.code, 0);
assertEquals(result.stdout, "yup\n");
}
{
const result = await builder.command("false && echo nope").noThrow();
assertEquals(result.code, 1);
assertEquals(result.stdout, "");
}
});
Deno.test("should not allow invalid command names", () => {
const builder = new CommandBuilder();
const hax: CommandHandler = (context: CommandContext) => {
context.stdout.writeLine("h4x!1!");
return {
code: 0,
};
};
assertThrows(
() => builder.registerCommand("/dev/null", hax),
Error,
"Invalid command name",
);
assertThrows(
() => builder.registerCommand("*", hax),
Error,
"Invalid command name",
);
});
Deno.test("should unregister commands", async () => {
const builder = new CommandBuilder().unregisterCommand("export").noThrow();
const output = await builder.command("export somewhere").stderr("piped");
assertEquals(output.code, 127);
assertEquals(output.stderr, "dax: export: command not found\n");
});
Deno.test("sleep command", async () => {
const start = performance.now();
const result = await $`sleep 0.2 && echo 1`.text();
const end = performance.now();
assertEquals(result, "1");
assertEquals(end - start > 190, true);
});
Deno.test("test command", async (t) => {
await Deno.writeFile("zero.dat", new Uint8Array());
await Deno.writeFile("non-zero.dat", new Uint8Array([242]));
if (Deno.build.os !== "windows") {
await Deno.symlink("zero.dat", "linked.dat");
}
await t.step("test -e", async () => {
const result = await $`test -e zero.dat`.noThrow();
assertEquals(result.code, 0);
});
await t.step("test -f", async () => {
const result = await $`test -f zero.dat`.noThrow();
assertEquals(result.code, 0, "should be a file");
});
await t.step("test -f on non-file", async () => {
const result = await $`test -f ${Deno.cwd()}`.noThrow().stderr("piped");
assertEquals(result.code, 1, "should not be a file");
assertEquals(result.stderr, "");
});
await t.step("test -d", async () => {
const result = await $`test -d ${Deno.cwd()}`.noThrow();
assertEquals(result.code, 0, `${Deno.cwd()} should be a directory`);
});
await t.step("test -d on non-directory", async () => {
const result = await $`test -d zero.dat`.noThrow().stderr("piped");
assertEquals(result.code, 1, "should not be a directory");
assertEquals(result.stderr, "");
});
await t.step("test -s", async () => {
const result = await $`test -s non-zero.dat`.noThrow().stderr("piped");
assertEquals(result.code, 0, "should be > 0");
assertEquals(result.stderr, "");
});
await t.step("test -s on zero-length file", async () => {
const result = await $`test -s zero.dat`.noThrow().stderr("piped");
assertEquals(result.code, 1, "should fail as file is zero-sized");
assertEquals(result.stderr, "");
});
if (Deno.build.os !== "windows") {
await t.step("test -L", async () => {
const result = await $`test -L linked.dat`.noThrow();
assertEquals(result.code, 0, "should be a symlink");
});
}
await t.step("test -L on a non-symlink", async () => {
const result = await $`test -L zero.dat`.noThrow().stderr("piped");
assertEquals(result.code, 1, "should fail as not a symlink");
assertEquals(result.stderr, "");
});
await t.step("should error on unsupported test type", async () => {
const result = await $`test -z zero.dat`.noThrow().stderr("piped");
assertEquals(result.code, 2, "should have exit code 2");
assertEquals(result.stderr, "test: unsupported test type\n");
});
await t.step("should error with not enough arguments", async () => {
const result = await $`test`.noThrow().stderr("piped");
assertEquals(result.code, 2, "should have exit code 2");
assertEquals(result.stderr, "test: expected 2 arguments\n");
});
await t.step("should error with too many arguments", async () => {
const result = await $`test -f a b c`.noThrow().stderr("piped");
assertEquals(result.code, 2, "should have exit code 2");
assertEquals(result.stderr, "test: expected 2 arguments\n");
});
await t.step("should work with boolean: pass && ..", async () => {
const result = await $`test -f zero.dat && echo yup`.noThrow().stdout("piped");
assertEquals(result.code, 0);
assertEquals(result.stdout, "yup\n");
});
await t.step("should work with boolean: fail && ..", async () => {
const result = await $`test -f ${Deno.cwd()} && echo nope`.noThrow().stdout("piped");
assertEquals(result.code, 1), "should have exit code 1";
assertEquals(result.stdout, "");
});
await t.step("should work with boolean: pass || ..", async () => {
const result = await $`test -f zero.dat || echo nope`.noThrow().stdout("piped");
assertEquals(result.code, 0);
assertEquals(result.stdout, "");
});
await t.step("should work with boolean: fail || ..", async () => {
const result = await $`test -f ${Deno.cwd()} || echo yup`.noThrow().stdout("piped");
assertEquals(result.code, 0);
assertEquals(result.stdout, "yup\n");
});
if (Deno.build.os !== "windows") {
await Deno.remove("linked.dat");
}
await Deno.remove("zero.dat");
await Deno.remove("non-zero.dat");
});
Deno.test("exit command", async () => {
{
const result = await $`exit`.noThrow();
assertEquals(result.code, 1);
}
{
const result = await $`exit 0`.noThrow();
assertEquals(result.code, 0);
}
{
const result = await $`exit 255`.noThrow();
assertEquals(result.code, 255);
}
{
const result = await $`exit 256`.noThrow();
assertEquals(result.code, 0);
}
{
const result = await $`exit 257`.noThrow();
assertEquals(result.code, 1);
}
{
const result = await $`exit -1`.noThrow();
assertEquals(result.code, 255);
}
{
const result = await $`exit zardoz`.noThrow().stderr("piped");
assertEquals(result.code, 2);
assertEquals(result.stderr, "exit: numeric argument required.\n");
}
{
const result = await $`exit 1 1`.noThrow().stderr("piped");
assertEquals(result.code, 2);
assertEquals(result.stderr, "exit: too many arguments\n");
}
// test noThrow with exit code
{
const result = await $`exit 255`.noThrow(255);
assertEquals(result.code, 255);
}
{
const result = await $`exit 255`.noThrow(254, 255);
assertEquals(result.code, 255);
}
{
await assertRejects(() => $`exit 255`.noThrow(254));
}
});
Deno.test("should provide result from one command to another", async () => {
const result = await $`echo 1`.stdout("piped");
const result2 = await $`echo ${result}`.stdout("piped");
assertEquals(result2.stdout, "1\n");
});
Deno.test("should actually change the environment when using .exportEnv()", async () => {
const originalDir = Deno.cwd();
try {
const srcDir = path.resolve("./src");
await $`cd src && export SOME_VALUE=5 && OTHER_VALUE=6`.exportEnv();
assertEquals(Deno.cwd(), srcDir);
assertEquals(Deno.env.get("SOME_VALUE"), "5");
assertEquals(Deno.env.get("OTHER_VALUE"), undefined);
} finally {
Deno.chdir(originalDir);
}
});
Deno.test("exporting env should modify real environment when something changed via the api", async () => {
const previousCwd = Deno.cwd();
const envName = "DAX_TEST_ENV_SET";
try {
await $`echo 2`
.cwd("./src")
.env(envName, "123")
.exportEnv();
assertEquals(Deno.env.get(envName), "123");
assertEquals(Deno.cwd().slice(-3), "src");
} finally {
Deno.env.delete(envName);
Deno.chdir(previousCwd);
}
});
Deno.test("setting an empty env var", async () => {
const text = await $`VAR= deno eval 'console.log("VAR: " + Deno.env.get("VAR"))'`.text();
assertEquals(text, "VAR: ");
});
Deno.test("unsetting env var", async () => {
const text = await $`unset VAR && deno eval 'console.log("VAR: " + Deno.env.get("VAR"))'`
.env("VAR", "1")
.text();
assertEquals(text, "VAR: undefined");
});
Deno.test("unsetting multiple env vars", async () => {
const text =
await $`unset VAR1 VAR2 && deno eval 'console.log("VAR: " + Deno.env.get("VAR1") + Deno.env.get("VAR2") + Deno.env.get("VAR3"))'`
.env({
"VAR1": "test",
"VAR2": "test",
"VAR3": "test",
})
.text();
assertEquals(text, "VAR: undefinedundefinedtest");
});
Deno.test("unsetting multiple shell vars", async () => {
const text = await $`VAR1=1 && VAR2=2 && VAR3=3 && VAR4=4 && unset VAR1 VAR4 && echo $VAR1 $VAR2 $VAR3 $VAR4`
.text();
assertEquals(text, "2 3");
});
Deno.test("unsetting shell var with -v", async () => {
const text = await $`VAR1=1 && unset -v VAR1 && echo $VAR1 test`
.text();
assertEquals(text, "test");
});
Deno.test("unsetting with no args", async () => {
const text = await $`unset && echo test`
.text();
assertEquals(text, "test");
});
Deno.test("unset with -f should error", async () => {
const result = await $`unset -f VAR1 && echo $VAR1`
.env({ "VAR1": "test" })
.stdout("piped")
.stderr("piped")
.noThrow();
assertEquals(result.code, 1);
assertEquals(result.stderr, "unset: unsupported flag: -f\n");
assertEquals(result.stdout, "");
});
Deno.test("cwd should be resolved based on cwd at time of method call and not execution", async () => {
await withTempDir(async (tempDir) => {
await tempDir.join("./src/rs_lib").ensureDir();
const command = $`echo $PWD`.cwd("./src");
Deno.chdir("./src/rs_lib");
const result = await command.text();
assertEquals(result.slice(-3), "src");
});
});
Deno.test("should handle the PWD variable", async () => {
const srcDir = path.resolve("./src");
{
const output = await $`cd src && echo $PWD `.text();
assertEquals(output, srcDir);
}
{
// changing PWD should affect this
const output = await $`PWD=$PWD/src && echo $PWD `.text();
assertEquals(output, srcDir);
}
});
Deno.test("timeout", async () => {
const command = $`deno eval 'await new Promise(resolve => setTimeout(resolve, 10_000));'`
.timeout(200);
await assertRejects(async () => await command, Error, "Timed out with exit code: 124");
const result = await command.noThrow();
assertEquals(result.code, 124);
});
Deno.test("abort", async () => {
const command = $`echo 1 && sleep 100 && echo 2`;
await assertRejects(
async () => {
const child = command.spawn();
child.kill();
await child;
},
Error,
"Aborted with exit code: 124",
);
const child = command.noThrow().spawn();
child.kill();
const result = await child;
assertEquals(result.code, 124);
});
Deno.test("piping to stdin", async (t) => {
await t.step("reader", async () => {
const bytes = new TextEncoder().encode("test\n");
const result =
await $`deno eval "const b = new Uint8Array(4); await Deno.stdin.read(b); await Deno.stdout.write(b);"`
.stdin(new Buffer(bytes))
.text();
assertEquals(result, "test");
});
await t.step("string", async () => {
const command = $`deno eval "const b = new Uint8Array(4); await Deno.stdin.read(b); await Deno.stdout.write(b);"`
.stdinText("test\n");
// should support calling multiple times
assertEquals(await command.text(), "test");
assertEquals(await command.text(), "test");
});
await t.step("Uint8Array", async () => {
const result =
await $`deno eval "const b = new Uint8Array(4); await Deno.stdin.read(b); await Deno.stdout.write(b);"`
.stdin(new TextEncoder().encode("test\n"))
.text();
assertEquals(result, "test");
});
await t.step("readable stream", async () => {
const child = $`echo 1 && echo 2`.stdout("piped").spawn();
const result = await $`deno eval 'await Deno.stdin.readable.pipeTo(Deno.stdout.writable);'`
.stdin(child.stdout())
.text();
assertEquals(result, "1\n2");
});
await t.step("Path", async () => {
await using tempDir = usingTempDir();
const tempFile = tempDir.join("temp_file.txt");
const fileText = "1 testing this out\n".repeat(1_000);
tempFile.writeTextSync(fileText);
const output = await $`cat`.stdin(tempFile).text();
assertEquals(output, fileText.trim());
});
await t.step("command via stdin", async () => {
const child = $`echo 1 && echo 2`;
const result = await $`deno eval 'await Deno.stdin.readable.pipeTo(Deno.stdout.writable);'`
.stdin(child)
.text();
assertEquals(result, "1\n2");
});
await t.step("command that exits via stdin", async () => {
const child = $`echo 1 && echo 2 && exit 1`;
const result = await $`deno eval 'await Deno.stdin.readable.pipeTo(Deno.stdout.writable);'`
.stdin(child)
.stderr("piped")
.noThrow();
assertEquals(result.code, 1);
assertEquals(result.stderr, "stdin pipe broken. Exited with code: 1\n");
});
});
Deno.test("pipe", async () => {
{
const result = await $`echo 1 && echo 2`
.pipe($`deno eval 'await Deno.stdin.readable.pipeTo(Deno.stderr.writable);'`)
.stderr("piped")
.stdout("piped")
.spawn();
assertEquals(result.stdout, "");
assertEquals(result.stderr, "1\n2\n");
}
});
Deno.test("piping to a writable and the command fails", async () => {
const chunks = [];
let wasClosed = false;
const writableStream = new WritableStream({
write(chunk) {
chunks.push(chunk);
},
close() {
wasClosed = true;
},
});
await $`echo 1 ; exit 1`.stdout(writableStream).noThrow();
assertEquals(chunks.length, 1);
assert(wasClosed);
});
Deno.test("piping to a writable and the command fails and throws", async () => {
const chunks = [];
let wasClosed = false;
const writableStream = new WritableStream({
write(chunk) {
chunks.push(chunk);
},
close() {
wasClosed = true;
},
});
let didThrow = false;
try {
await $`echo 1 ; exit 1`.stdout(writableStream);
} catch {
didThrow = true;
}
assert(didThrow);
assertEquals(chunks.length, 1);
assert(wasClosed);
});
Deno.test("piping to a writable that throws", async () => {
const writableStream = new WritableStream({
write(_chunk) {
throw new Error("failed");
},
});
const result = await $`echo 1`.stdout(writableStream).stderr("piped").noThrow();
assertEquals(result.code, 1);
assertEquals(result.stderr, "echo: failed\n");
});
Deno.test("piping stdout/stderr to a file", async () => {
await withTempDir(async (tempDir) => {
const tempFile = tempDir.join("temp_file.txt");
await $`echo 1`.stdout(tempFile);
assertEquals(tempFile.readTextSync(), "1\n");
});
await withTempDir(async (tempDir) => {
const tempFile = tempDir.join("temp_file.txt");
await $`deno eval 'console.error(1);'`
.env("NO_COLOR", "1")
.stderr(tempFile);
assertEquals(tempFile.readTextSync(), "1\n");
});
await withTempDir(async (tempDir) => {
const tempFile = tempDir.join("temp_file.txt");
{
using file = tempFile.openSync({ write: true, create: true, truncate: true });
await $`deno eval "console.log('1234\\n'.repeat(1_000));"`.stdout(file.writable);
}
const text = tempFile.readTextSync();
// last \n for the console.log itself
assertEquals(text, "1234\n".repeat(1_000) + "\n");
});
});
Deno.test("spawning a command twice that has stdin set to a Reader should error", async () => {
const bytes = new TextEncoder().encode("test\n");
const command = $`deno eval "const b = new Uint8Array(4); await Deno.stdin.read(b); await Deno.stdout.write(b);"`
.stdin(new Buffer(bytes));
const result = await command.text();
assertEquals(result, "test");
await assertRejects(
() => command.text(),
Error,
"Cannot spawn command. Stdin was already consumed when a previous command using the same stdin " +
"was spawned. You need to call `.stdin(...)` again with a new value before spawning.",
);
});
Deno.test("streaming api not piped", async () => {
const child = $`echo 1 && echo 2`.spawn();
assertThrows(
() => child.stdout(),
Error,
`No pipe available. Ensure stdout is "piped" (not "inheritPiped") and combinedOutput is not enabled.`,
);
assertThrows(
() => child.stderr(),
Error,
`No pipe available. Ensure stderr is "piped" (not "inheritPiped") and combinedOutput is not enabled.`,
);
await child;
});
Deno.test("streaming api then non-streaming should error", async () => {
const child = $`echo 1 && echo 2`.stdout("piped").stderr("piped").spawn();
const stdout = readerFromStreamReader(child.stdout().getReader());
const stderr = readerFromStreamReader(child.stderr().getReader());
const result = await child;
// ensure these are all read to prevent issues with sanitizers
await readAll(stdout);
await readAll(stderr);