-
Notifications
You must be signed in to change notification settings - Fork 0
/
command_test.go
993 lines (911 loc) · 27.2 KB
/
command_test.go
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
package cli_test
import (
"bytes"
"errors"
goflag "flag"
"fmt"
"io"
"math/rand/v2"
"os"
"slices"
"testing"
"github.com/FollowTheProcess/cli"
"github.com/FollowTheProcess/snapshot"
"github.com/FollowTheProcess/test"
)
var (
debug = goflag.Bool("debug", false, "Print debug output during tests")
update = goflag.Bool("update", false, "Update golden files")
)
func TestExecute(t *testing.T) {
tests := []struct {
name string // Name of the test case
stdout string // Expected output to stdout
stderr string // Expected output to stderr
options []cli.Option // Options to apply to the test command
wantErr bool // Whether we want an error or not
}{
{
name: "simple",
stdout: "My arguments were: [hello there]\nForce was: false\n",
stderr: "",
options: []cli.Option{
cli.OverrideArgs([]string{"hello", "there"}),
cli.Stdin(os.Stdin), // Set stdin for the lols
},
wantErr: false,
},
{
name: "simple with flag",
stdout: "My arguments were: [hello there]\nForce was: true\n",
stderr: "",
options: []cli.Option{
cli.OverrideArgs([]string{"hello", "there", "--force"}),
},
wantErr: false,
},
{
name: "bad flag",
stdout: "",
stderr: "",
options: []cli.Option{
cli.OverrideArgs([]string{"arg1", "arg2", "arg3", "-]force"}),
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var force bool
stderr := &bytes.Buffer{}
stdout := &bytes.Buffer{}
// Test specific overrides to the options in the table
options := []cli.Option{
cli.Stdout(stdout),
cli.Stderr(stderr),
cli.Run(func(cmd *cli.Command, args []string) error {
fmt.Fprintf(cmd.Stdout(), "My arguments were: %v\nForce was: %v\n", args, force)
return nil
}),
cli.Flag(&force, "force", 'f', false, "Force something"),
}
cmd, err := cli.New("test", slices.Concat(options, tt.options)...)
test.Ok(t, err)
err = cmd.Execute()
test.WantErr(t, err, tt.wantErr)
test.Equal(t, stdout.String(), tt.stdout)
test.Equal(t, stderr.String(), tt.stderr)
})
}
}
func TestSubCommandExecute(t *testing.T) {
tests := []struct {
name string // Test case name
stdout string // Expected stdout
stderr string // Expected stderr
args []string // Args passed to root command
extra []string // Extra args after "--" if present
wantErr bool // Whether or not we wanted an error
}{
{
name: "invoke sub1 no flags",
stdout: "Hello from sub1, my args were: [my subcommand args], force was false, something was <empty>, extra args: []",
stderr: "",
args: []string{"sub1", "my", "subcommand", "args"},
wantErr: false,
},
{
name: "invoke sub2 no flags",
stdout: "Hello from sub2, my args were: [my different args], delete was false, number was -1",
stderr: "",
args: []string{"sub2", "my", "different", "args"},
wantErr: false,
},
{
name: "invoke sub1 with flags",
stdout: "Hello from sub1, my args were: [my subcommand args], force was true, something was here, extra args: []",
stderr: "",
args: []string{"sub1", "my", "subcommand", "args", "--force", "--something", "here"},
wantErr: false,
},
{
name: "invoke sub1 with arg terminator",
stdout: "Hello from sub1, my args were: [my subcommand args more args here], force was true, something was here, extra args: [more args here]",
stderr: "",
args: []string{"sub1", "my", "subcommand", "args", "--force", "--something", "here", "--", "more", "args", "here"},
wantErr: false,
},
{
name: "invoke sub1 with sub1 in the arg list",
stdout: "Hello from sub1, my args were: [my sub1 args sub1 more args here], force was true, something was here, extra args: []",
stderr: "",
args: []string{"sub1", "my", "sub1", "args", "sub1", "--force", "--something", "here", "more", "args", "here"},
wantErr: false,
},
{
name: "invoke sub1 with sub1 as a flag value",
stdout: "Hello from sub1, my args were: [my subcommand args more args here], force was true, something was sub2, extra args: []",
stderr: "",
args: []string{"sub1", "my", "subcommand", "args", "--force", "--something", "sub2", "more", "args", "here"},
wantErr: false,
},
{
name: "invoke root with no args",
stdout: "",
stderr: "",
args: []string{},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var (
force bool
something string
deleteMe bool
number int
stdoutBuf = &bytes.Buffer{}
stderrBuf = &bytes.Buffer{}
)
sub1 := func() (*cli.Command, error) {
return cli.New(
"sub1",
cli.Run(func(cmd *cli.Command, args []string) error {
if something == "" {
something = "<empty>"
}
extra, ok := cmd.ExtraArgs()
if !ok {
extra = []string{}
}
fmt.Fprintf(
cmd.Stdout(),
"Hello from sub1, my args were: %v, force was %v, something was %s, extra args: %v",
args,
force,
something,
extra,
)
return nil
}),
cli.Flag(&force, "force", 'f', false, "Force for sub1"),
cli.Flag(&something, "something", 's', "", "Something for sub1"),
)
}
sub2 := func() (*cli.Command, error) {
return cli.New(
"sub2",
cli.Run(func(cmd *cli.Command, args []string) error {
fmt.Fprintf(
cmd.Stdout(),
"Hello from sub2, my args were: %v, delete was %v, number was %d",
args,
deleteMe,
number,
)
return nil
}),
cli.Flag(&deleteMe, "delete", 'd', false, "Delete for sub2"),
cli.Flag(&number, "number", 'n', -1, "Number for sub2"),
)
}
root, err := cli.New(
"root",
cli.SubCommands(sub1, sub2),
cli.Stdout(stdoutBuf),
cli.Stderr(stderrBuf),
cli.OverrideArgs(tt.args),
)
test.Ok(t, err)
// Execute the command, we should see the sub commands get executed based on what args we provide
err = root.Execute()
test.WantErr(t, err, tt.wantErr)
if !tt.wantErr {
test.Equal(t, stdoutBuf.String(), tt.stdout)
test.Equal(t, stderrBuf.String(), tt.stderr)
}
})
}
}
func TestPositionalArgs(t *testing.T) {
sub := func() (*cli.Command, error) {
return cli.New(
"sub",
cli.Short("Sub command"),
cli.Arg("subarg", "Argument given to a subcommand", ""),
cli.Run(func(cmd *cli.Command, args []string) error {
fmt.Fprintf(cmd.Stdout(), "Hello from sub command, subarg: %s", cmd.Arg("subarg"))
return nil
}),
)
}
tests := []struct {
name string // The name of the test case
stdout string // The expected stdout
errMsg string // If we did want an error, what should it say
options []cli.Option // Options to apply to the command under test
args []string // Arguments to be passed to the command
wantErr bool // Whether we want an error
}{
{
name: "required and given",
options: []cli.Option{
cli.Arg("file", "The path to a file", ""), // "" means required
cli.Run(func(cmd *cli.Command, args []string) error {
fmt.Fprintf(cmd.Stdout(), "file was %s\n", cmd.Arg("file"))
return nil
}),
},
stdout: "file was something.txt\n",
args: []string{"something.txt"},
wantErr: false,
},
{
name: "required but missing",
options: []cli.Option{
cli.Arg("file", "The path to a file", ""), // "" means required
cli.Run(func(cmd *cli.Command, args []string) error {
fmt.Fprintf(cmd.Stdout(), "file was %s\n", cmd.Arg("file"))
return nil
}),
},
stdout: "",
args: []string{},
wantErr: true,
errMsg: `missing required argument "file", expected at position 0`, // Comes from command.Execute
},
{
name: "optional and given",
options: []cli.Option{
cli.Arg("file", "The path to a file", "default.txt"), // This time it has a default
cli.Run(func(cmd *cli.Command, args []string) error {
fmt.Fprintf(cmd.Stdout(), "file was %s\n", cmd.Arg("file"))
return nil
}),
},
stdout: "file was something.txt\n",
args: []string{"something.txt"},
wantErr: false,
},
{
name: "optional and missing",
options: []cli.Option{
cli.Arg("file", "The path to a file", "default.txt"), // This time it has a default
cli.Run(func(cmd *cli.Command, args []string) error {
fmt.Fprintf(cmd.Stdout(), "file was %s\n", cmd.Arg("file"))
return nil
}),
},
stdout: "file was default.txt\n", // Should fall back to the default
args: []string{},
wantErr: false,
},
{
name: "several args all given",
options: []cli.Option{
cli.Arg("src", "The path to the source file", ""), // File required as first arg
cli.Arg("dest", "The destination path", "dest.txt"), // Dest has a default
cli.Arg("something", "Another arg", ""), // Required again
cli.Run(func(cmd *cli.Command, args []string) error {
fmt.Fprintf(cmd.Stdout(), "src: %s, dest: %s, something: %s\n", cmd.Arg("src"), cmd.Arg("dest"), cmd.Arg("something"))
return nil
}),
},
stdout: "src: src.txt, dest: other-dest.txt, something: yes\n",
args: []string{"src.txt", "other-dest.txt", "yes"}, // Give all 3 args
wantErr: false,
},
{
name: "several args one missing",
options: []cli.Option{
cli.Arg("src", "The path to the source file", ""), // File required as first arg
cli.Arg("dest", "The destination path", "default-dest.txt"), // Dest has a default
cli.Arg("something", "Another arg", ""), // Required again
cli.Run(func(cmd *cli.Command, args []string) error {
fmt.Fprintf(cmd.Stdout(), "src: %s, dest: %s, something: %s\n", cmd.Arg("src"), cmd.Arg("dest"), cmd.Arg("something"))
return nil
}),
},
stdout: "",
args: []string{"src.txt"}, // arg 'something' is missing, dest will use its default
wantErr: true,
errMsg: `missing required argument "something", expected at position 2`,
},
{
name: "subcommand with named arg",
options: []cli.Option{
cli.SubCommands(sub),
},
stdout: "Hello from sub command, subarg: blah",
args: []string{"sub", "blah"}, // subarg should be "blah"
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
stdout := &bytes.Buffer{}
// Test specific overrides to the options in the table
options := []cli.Option{
cli.Stdout(stdout),
cli.OverrideArgs(tt.args),
}
cmd, err := cli.New("posargs", slices.Concat(options, tt.options)...)
test.Ok(t, err) // cli.New returned an error
err = cmd.Execute()
test.WantErr(t, err, tt.wantErr)
test.Equal(t, stdout.String(), tt.stdout)
if err != nil {
test.Equal(t, err.Error(), tt.errMsg) // Error messages don't match
}
})
}
}
func TestHelp(t *testing.T) {
sub1 := func() (*cli.Command, error) {
return cli.New(
"sub1",
cli.Short("Do one thing"),
cli.Run(func(cmd *cli.Command, args []string) error {
fmt.Fprintln(cmd.Stdout(), "Hello from sub1")
return nil
}))
}
sub2 := func() (*cli.Command, error) {
return cli.New(
"sub2",
cli.Short("Do another thing"),
cli.Run(func(cmd *cli.Command, args []string) error {
fmt.Fprintln(cmd.Stdout(), "Hello from sub2")
return nil
}),
)
}
sub3 := func() (*cli.Command, error) {
return cli.New(
"very-long-subcommand",
cli.Short("Wow so long"),
cli.Run(func(cmd *cli.Command, args []string) error {
fmt.Fprintln(cmd.Stdout(), "Hello from sub3")
return nil
}),
)
}
tests := []struct {
name string // Identifier of the test case
options []cli.Option // Options to apply to the command
wantErr bool // Whether we want an error
}{
{
name: "default long",
options: []cli.Option{
cli.OverrideArgs([]string{"--help"}),
cli.Run(func(cmd *cli.Command, args []string) error { return nil }),
},
wantErr: false,
},
{
name: "default.short",
options: []cli.Option{
cli.OverrideArgs([]string{"-h"}),
cli.Run(func(cmd *cli.Command, args []string) error { return nil }),
},
wantErr: false,
},
{
name: "with examples",
options: []cli.Option{
cli.OverrideArgs([]string{"--help"}),
cli.Example("Do a thing", "test do thing --now"),
cli.Example("Do a different thing", "test do thing --different"),
cli.Run(func(cmd *cli.Command, args []string) error { return nil }),
},
wantErr: false,
},
{
name: "with named arguments",
options: []cli.Option{
cli.OverrideArgs([]string{"--help"}),
cli.Arg("src", "The file to copy", ""), // This one is required
cli.Arg("dest", "Destination to copy to", "./dest"), // This one is optional
cli.Run(func(cmd *cli.Command, args []string) error { return nil }),
},
wantErr: false,
},
{
name: "with verbosity count",
options: []cli.Option{
cli.OverrideArgs([]string{"--help"}),
cli.Arg("src", "The file to copy", ""), // This one is required
cli.Arg("dest", "Destination to copy to", "./dest"), // This one is optional
cli.Flag(new(cli.FlagCount), "verbosity", 'v', 0, "Increase the verbosity level"),
cli.Run(func(cmd *cli.Command, args []string) error { return nil }),
},
wantErr: false,
},
{
name: "with full description",
options: []cli.Option{
cli.OverrideArgs([]string{"--help"}),
cli.Short("A cool CLI to do things"),
cli.Long("A longer, probably multiline description"),
cli.Run(func(cmd *cli.Command, args []string) error { return nil }),
},
wantErr: false,
},
{
name: "with no description",
options: []cli.Option{
cli.OverrideArgs([]string{"--help"}),
cli.Run(func(cmd *cli.Command, args []string) error { return nil }),
},
wantErr: false,
},
{
name: "with subcommands",
options: []cli.Option{
cli.OverrideArgs([]string{"--help"}),
cli.Short("A cool CLI to do things"),
cli.Long("A longer, probably multiline description"),
cli.SubCommands(sub1, sub2),
},
wantErr: false,
},
{
name: "subcommands different lengths",
options: []cli.Option{
cli.OverrideArgs([]string{"--help"}),
cli.Short("A cool CLI to do things"),
cli.Long("A longer, probably multiline description"),
cli.SubCommands(sub1, sub2, sub3),
},
wantErr: false,
},
{
name: "with subcommands and flags",
options: []cli.Option{
cli.OverrideArgs([]string{"--help"}),
cli.Short("A cool CLI to do things"),
cli.Long("A longer, probably multiline description"),
cli.SubCommands(sub1, sub2),
cli.Flag(new(bool), "delete", 'd', false, "Delete something"),
cli.Flag(new(int), "count", cli.NoShortHand, -1, "Count something"),
},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Force no colour in tests
t.Setenv("NO_COLOR", "true")
snap := snapshot.New(t, snapshot.Update(*update))
stderr := &bytes.Buffer{}
stdout := &bytes.Buffer{}
// Test specific overrides to the options in the table
options := []cli.Option{cli.Stdout(stdout), cli.Stderr(stderr)}
cmd, err := cli.New("test", slices.Concat(options, tt.options)...)
test.Ok(t, err)
err = cmd.Execute()
test.WantErr(t, err, tt.wantErr)
if *debug {
fmt.Printf("DEBUG\n_____\n\n%s\n", stderr.String())
}
// Should have no output to stdout
test.Equal(t, stdout.String(), "")
// --help output should be as per the snapshot
snap.Snap(stderr.String())
})
}
}
func TestVersion(t *testing.T) {
tests := []struct {
name string // Name of the test case
stderr string // Expected output to stderr
options []cli.Option // Options to apply to the test command
wantErr bool // Whether we want an error or not
}{
{
name: "default long",
options: []cli.Option{
cli.OverrideArgs([]string{"--version"}),
cli.Run(func(cmd *cli.Command, args []string) error { return nil }),
},
stderr: "version-test\n\nVersion: dev\n",
wantErr: false,
},
{
name: "default short",
options: []cli.Option{
cli.OverrideArgs([]string{"-V"}),
cli.Run(func(cmd *cli.Command, args []string) error { return nil }),
},
stderr: "version-test\n\nVersion: dev\n",
wantErr: false,
},
{
name: "with version",
options: []cli.Option{
cli.OverrideArgs([]string{"--version"}),
cli.Version("v3.1.7"),
cli.Run(func(cmd *cli.Command, args []string) error { return nil }),
},
stderr: "version-test\n\nVersion: v3.1.7\n",
wantErr: false,
},
{
name: "with commit",
options: []cli.Option{
cli.OverrideArgs([]string{"--version"}),
cli.Commit("eedb45b"),
cli.Run(func(cmd *cli.Command, args []string) error { return nil }),
},
stderr: "version-test\n\nVersion: dev\nCommit: eedb45b\n",
wantErr: false,
},
{
name: "with build date",
options: []cli.Option{
cli.OverrideArgs([]string{"--version"}),
cli.BuildDate("2024-04-11T02:23:42Z"),
cli.Run(func(cmd *cli.Command, args []string) error { return nil }),
},
stderr: "version-test\n\nVersion: dev\nBuildDate: 2024-04-11T02:23:42Z\n",
wantErr: false,
},
{
name: "with version and commit",
options: []cli.Option{
cli.OverrideArgs([]string{"--version"}),
cli.Version("v8.17.6"),
cli.Commit("b9aaafd"),
cli.Run(func(cmd *cli.Command, args []string) error { return nil }),
},
stderr: "version-test\n\nVersion: v8.17.6\nCommit: b9aaafd\n",
wantErr: false,
},
{
name: "with all",
options: []cli.Option{
cli.OverrideArgs([]string{"--version"}),
cli.Version("v8.17.6"),
cli.Commit("b9aaafd"),
cli.BuildDate("2024-08-17T10:37:30Z"),
cli.Run(func(cmd *cli.Command, args []string) error { return nil }),
},
stderr: "version-test\n\nVersion: v8.17.6\nCommit: b9aaafd\nBuildDate: 2024-08-17T10:37:30Z\n",
wantErr: false,
},
{
name: "custom versionFunc",
options: []cli.Option{
cli.OverrideArgs([]string{"--version"}),
cli.VersionFunc(func(cmd *cli.Command) error {
fmt.Fprintln(cmd.Stderr(), "Do something custom here")
return nil
}),
cli.Run(func(cmd *cli.Command, args []string) error { return nil }),
},
stderr: "Do something custom here\n",
wantErr: false,
},
{
name: "return error",
options: []cli.Option{
cli.OverrideArgs([]string{"--version"}),
cli.VersionFunc(func(cmd *cli.Command) error {
return errors.New("Uh oh!")
}),
cli.Run(func(cmd *cli.Command, args []string) error { return nil }),
},
stderr: "",
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Force no colour in tests
t.Setenv("NO_COLOR", "true")
stderr := &bytes.Buffer{}
stdout := &bytes.Buffer{}
// Test specific overrides to the options in the table
options := []cli.Option{cli.Stdout(stdout), cli.Stderr(stderr)}
cmd, err := cli.New("version-test", slices.Concat(tt.options, options)...)
test.Ok(t, err)
err = cmd.Execute()
test.WantErr(t, err, tt.wantErr)
// Should have no output to stdout
test.Equal(t, stdout.String(), "")
// --version output should be as desired
test.Equal(t, stderr.String(), tt.stderr)
})
}
}
func TestOptionValidation(t *testing.T) {
tests := []struct {
name string // Name of the test case
errMsg string // If we wanted an error, what should it say
options []cli.Option // Options to apply to the command
}{
{
name: "nil stdin",
options: []cli.Option{cli.Stdin(nil)},
errMsg: "cannot set Stdin to nil",
},
{
name: "nil stdout",
options: []cli.Option{cli.Stdout(nil)},
errMsg: "cannot set Stdout to nil",
},
{
name: "nil stderr",
options: []cli.Option{cli.Stderr(nil)},
errMsg: "cannot set Stderr to nil",
},
{
name: "nil all three",
options: []cli.Option{cli.Stdout(nil), cli.Stderr(nil), cli.Stdin(nil)},
errMsg: "cannot set Stdout to nil\ncannot set Stderr to nil\ncannot set Stdin to nil",
},
{
name: "nil args",
options: []cli.Option{cli.OverrideArgs(nil)},
errMsg: "cannot set Args to nil",
},
{
name: "nil VersionFunc",
options: []cli.Option{cli.VersionFunc(nil)},
errMsg: "cannot set VersionFunc to nil",
},
{
name: "nil Run",
options: []cli.Option{cli.Run(nil)},
errMsg: "cannot set Run to nil",
},
{
name: "nil ArgValidator",
options: []cli.Option{cli.Allow(nil)},
errMsg: "cannot set Allow to a nil ArgValidator",
},
{
name: "flag already exists",
options: []cli.Option{
cli.Flag(new(int), "count", 'c', 0, "Count something"),
cli.Flag(new(int), "count", 'c', 0, "Count something (again)"),
},
errMsg: `flag "count" already defined`,
},
{
name: "flag short already exists",
options: []cli.Option{
cli.Flag(new(int), "count", 'c', 0, "Count something"),
cli.Flag(new(string), "config", 'c', "", "Path to config file"),
},
errMsg: `could not add flag "config" to command "test": shorthand "c" already in use for flag "count"`,
},
{
name: "example comment empty",
options: []cli.Option{cli.Example("", "command here")},
errMsg: "example comment cannot be empty",
},
{
name: "example command empty",
options: []cli.Option{cli.Example("comment here", "")},
errMsg: "example command cannot be empty",
},
{
name: "empty short description",
options: []cli.Option{cli.Short("")},
errMsg: "cannot set command short description to an empty string",
},
{
name: "empty long description",
options: []cli.Option{cli.Long("")},
errMsg: "cannot set command long description to an empty string",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := cli.New("test", tt.options...)
test.Err(t, err)
test.Equal(t, err.Error(), tt.errMsg)
})
}
}
func TestDuplicateSubCommands(t *testing.T) {
sub1 := func() (*cli.Command, error) {
return cli.New(
"sub1",
cli.Run(func(cmd *cli.Command, args []string) error { return nil }),
)
}
sub2 := func() (*cli.Command, error) {
return cli.New(
"sub2",
cli.Run(func(cmd *cli.Command, args []string) error { return nil }),
)
}
sub1Again := func() (*cli.Command, error) {
return cli.New(
"sub1",
cli.Run(func(cmd *cli.Command, args []string) error { return nil }),
)
}
_, err := cli.New(
"root",
cli.SubCommands(sub1, sub2, sub1Again), // This should cause the error
)
test.Err(t, err)
if err != nil {
test.Equal(t, err.Error(), `subcommand "sub1" already defined`)
}
}
func TestCommandNoRunNoSub(t *testing.T) {
_, err := cli.New(
"root",
cli.OverrideArgs([]string{}),
// Run function missing and no subcommand
)
test.Err(t, err)
}
func TestExecuteNilCommand(t *testing.T) {
var cmd *cli.Command
err := cmd.Execute()
test.Err(t, err)
if err != nil {
test.Equal(t, err.Error(), "Execute called on a nil Command")
}
}
// The order in which we apply options shouldn't matter, this test
// shuffles the order of the options and asserts the Command we get
// out behaves the same as a baseline.
func TestCommandOptionOrder(t *testing.T) {
baseLineStdout := &bytes.Buffer{}
baseLineStderr := &bytes.Buffer{}
shuffleStdout := &bytes.Buffer{}
shuffleStderr := &bytes.Buffer{}
var (
f bool
count int
)
sub := func() (*cli.Command, error) {
return cli.New(
"sub",
cli.Run(func(cmd *cli.Command, args []string) error {
fmt.Fprintln(cmd.Stdout(), "Hello from sub")
return nil
}),
)
}
options := []cli.Option{
cli.OverrideArgs([]string{"some", "args", "here", "--flag", "--count", "10"}),
cli.Short("Short description"),
cli.Long("Long description"),
cli.Example("Do a thing", "demo run something --flag"),
cli.Run(func(cmd *cli.Command, args []string) error {
fmt.Fprintf(cmd.Stdout(), "args: %v, flag: %v, count: %v\n", args, f, count)
return nil
}),
cli.Version("v1.2.3"),
cli.VersionFunc(func(cmd *cli.Command) error {
fmt.Println(cmd.Stderr(), "versionFunc")
return nil
}),
cli.Allow(cli.AnyArgs()),
cli.SubCommands(sub),
cli.Flag(&f, "flag", 'f', false, "Set a bool flag"),
cli.Flag(&count, "count", 'c', 0, "Count a thing"),
}
baseLineOptions := slices.Concat(
options,
[]cli.Option{
cli.Stderr(baseLineStderr), // Set output streams specific to the baseline
cli.Stdout(baseLineStdout),
})
baseline, err := cli.New("baseline", baseLineOptions...)
test.Ok(t, err)
err = baseline.Execute()
test.Ok(t, err)
// Make sure the baseline is behaving as expected
test.Equal(t, baseLineStdout.String(), "args: [some args here], flag: true, count: 10\n")
test.Equal(t, baseLineStderr.String(), "")
// Shuffley shuffle, 100 permutations should do it
for range 100 {
shuffled := shuffle(options)
// Set output streams specific to the shuffled command
shuffleOptions := slices.Concat(
shuffled,
[]cli.Option{
cli.Stderr(shuffleStderr),
cli.Stdout(shuffleStdout),
},
)
// Make a Command with the randomly ordered options
shuffle, err := cli.New("shuffle", shuffleOptions...)
test.Ok(t, err)
// The two commands should behave equivalently
err = shuffle.Execute()
test.Ok(t, err)
test.Equal(t, shuffleStdout.String(), baseLineStdout.String())
test.Equal(t, shuffleStderr.String(), baseLineStderr.String())
// Clear the buffers for the next loop
shuffleStderr.Reset()
shuffleStdout.Reset()
}
}
func BenchmarkExecuteHelp(b *testing.B) {
sub1 := func() (*cli.Command, error) {
return cli.New(
"sub1",
cli.Short("Do one thing"),
cli.Run(func(cmd *cli.Command, args []string) error {
fmt.Fprintln(cmd.Stdout(), "Hello from sub1")
return nil
}),
)
}
sub2 := func() (*cli.Command, error) {
return cli.New(
"sub2",
cli.Short("Do another thing"),
cli.Run(func(cmd *cli.Command, args []string) error {
fmt.Fprintln(cmd.Stdout(), "Hello from sub2")
return nil
}),
)
}
sub3 := func() (*cli.Command, error) {
return cli.New(
"very-long-subcommand",
cli.Short("Wow so long"),
cli.Run(func(cmd *cli.Command, args []string) error {
fmt.Fprintln(cmd.Stdout(), "Hello from sub3")
return nil
}),
)
}
cmd, err := cli.New(
"bench-help",
cli.Short("A helpful benchmark command"),
cli.Long("Much longer text..."),
cli.Example("Do a thing", "bench-help very-long-subcommand --flag"),
cli.SubCommands(sub1, sub2, sub3),
cli.OverrideArgs([]string{"--help"}),
cli.Stderr(io.Discard),
cli.Stdout(io.Discard),
)
test.Ok(b, err)
b.ResetTimer()
for range b.N {
err := cmd.Execute()
if err != nil {
b.Fatalf("Execute returned an error: %v", err)
}
}
}
// Benchmarks calling New to build a typical CLI.
func BenchmarkNew(b *testing.B) {
for range b.N {
_, err := cli.New(
"benchy",
cli.Short("A typical CLI to benchmark calling cli.New"),
cli.Version("dev"),
cli.Commit("dfdddaf"),
cli.Example("An example", "bench --help"),
cli.Allow(cli.AnyArgs()),
cli.Flag(new(bool), "force", 'f', false, "Force something"),
cli.Flag(new(string), "name", 'n', "", "The name of something"),
cli.Flag(new(int), "count", 'c', 1, "Count something"),
cli.Run(func(cmd *cli.Command, args []string) error { return nil }),
)
if err != nil {
b.Fatal(err)
}
}
}
// shuffle returns a randomly ordered copy of items.
func shuffle[T any](items []T) []T {
shuffled := slices.Clone(items)
rand.Shuffle(len(shuffled), func(i, j int) {
shuffled[i], shuffled[j] = shuffled[j], shuffled[i]
})
return shuffled
}