-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
command_test.go
2841 lines (2375 loc) · 75 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
994
995
996
997
998
999
1000
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cobra
import (
"bytes"
"context"
"fmt"
"io"
"os"
"reflect"
"strings"
"testing"
"github.com/spf13/pflag"
)
func emptyRun(*Command, []string) {}
func executeCommand(root *Command, args ...string) (output string, err error) {
_, output, err = executeCommandC(root, args...)
return output, err
}
func executeCommandWithContext(ctx context.Context, root *Command, args ...string) (output string, err error) {
buf := new(bytes.Buffer)
root.SetOut(buf)
root.SetErr(buf)
root.SetArgs(args)
err = root.ExecuteContext(ctx)
return buf.String(), err
}
func executeCommandC(root *Command, args ...string) (c *Command, output string, err error) {
buf := new(bytes.Buffer)
root.SetOut(buf)
root.SetErr(buf)
root.SetArgs(args)
c, err = root.ExecuteC()
return c, buf.String(), err
}
func executeCommandWithContextC(ctx context.Context, root *Command, args ...string) (c *Command, output string, err error) {
buf := new(bytes.Buffer)
root.SetOut(buf)
root.SetErr(buf)
root.SetArgs(args)
c, err = root.ExecuteContextC(ctx)
return c, buf.String(), err
}
func resetCommandLineFlagSet() {
pflag.CommandLine = pflag.NewFlagSet(os.Args[0], pflag.ExitOnError)
}
func checkStringContains(t *testing.T, got, expected string) {
if !strings.Contains(got, expected) {
t.Errorf("Expected to contain: \n %v\nGot:\n %v\n", expected, got)
}
}
func checkStringOmits(t *testing.T, got, expected string) {
if strings.Contains(got, expected) {
t.Errorf("Expected to not contain: \n %v\nGot: %v", expected, got)
}
}
const onetwo = "one two"
func TestSingleCommand(t *testing.T) {
var rootCmdArgs []string
rootCmd := &Command{
Use: "root",
Args: ExactArgs(2),
Run: func(_ *Command, args []string) { rootCmdArgs = args },
}
aCmd := &Command{Use: "a", Args: NoArgs, Run: emptyRun}
bCmd := &Command{Use: "b", Args: NoArgs, Run: emptyRun}
rootCmd.AddCommand(aCmd, bCmd)
output, err := executeCommand(rootCmd, "one", "two")
if output != "" {
t.Errorf("Unexpected output: %v", output)
}
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
got := strings.Join(rootCmdArgs, " ")
if got != onetwo {
t.Errorf("rootCmdArgs expected: %q, got: %q", onetwo, got)
}
}
func TestChildCommand(t *testing.T) {
var child1CmdArgs []string
rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}
child1Cmd := &Command{
Use: "child1",
Args: ExactArgs(2),
Run: func(_ *Command, args []string) { child1CmdArgs = args },
}
child2Cmd := &Command{Use: "child2", Args: NoArgs, Run: emptyRun}
rootCmd.AddCommand(child1Cmd, child2Cmd)
output, err := executeCommand(rootCmd, "child1", "one", "two")
if output != "" {
t.Errorf("Unexpected output: %v", output)
}
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
got := strings.Join(child1CmdArgs, " ")
if got != onetwo {
t.Errorf("child1CmdArgs expected: %q, got: %q", onetwo, got)
}
}
func TestCallCommandWithoutSubcommands(t *testing.T) {
rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}
_, err := executeCommand(rootCmd)
if err != nil {
t.Errorf("Calling command without subcommands should not have error: %v", err)
}
}
func TestRootExecuteUnknownCommand(t *testing.T) {
rootCmd := &Command{Use: "root", Run: emptyRun}
rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun})
output, _ := executeCommand(rootCmd, "unknown")
expected := "Error: unknown command \"unknown\" for \"root\"\nRun 'root --help' for usage.\n"
if output != expected {
t.Errorf("Expected:\n %q\nGot:\n %q\n", expected, output)
}
}
func TestSubcommandExecuteC(t *testing.T) {
rootCmd := &Command{Use: "root", Run: emptyRun}
childCmd := &Command{Use: "child", Run: emptyRun}
rootCmd.AddCommand(childCmd)
c, output, err := executeCommandC(rootCmd, "child")
if output != "" {
t.Errorf("Unexpected output: %v", output)
}
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if c.Name() != "child" {
t.Errorf(`invalid command returned from ExecuteC: expected "child"', got: %q`, c.Name())
}
}
func TestExecuteContext(t *testing.T) {
ctx := context.TODO()
ctxRun := func(cmd *Command, args []string) {
if cmd.Context() != ctx {
t.Errorf("Command %q must have context when called with ExecuteContext", cmd.Use)
}
}
rootCmd := &Command{Use: "root", Run: ctxRun, PreRun: ctxRun}
childCmd := &Command{Use: "child", Run: ctxRun, PreRun: ctxRun}
granchildCmd := &Command{Use: "grandchild", Run: ctxRun, PreRun: ctxRun}
childCmd.AddCommand(granchildCmd)
rootCmd.AddCommand(childCmd)
if _, err := executeCommandWithContext(ctx, rootCmd, ""); err != nil {
t.Errorf("Root command must not fail: %+v", err)
}
if _, err := executeCommandWithContext(ctx, rootCmd, "child"); err != nil {
t.Errorf("Subcommand must not fail: %+v", err)
}
if _, err := executeCommandWithContext(ctx, rootCmd, "child", "grandchild"); err != nil {
t.Errorf("Command child must not fail: %+v", err)
}
}
func TestExecuteContextC(t *testing.T) {
ctx := context.TODO()
ctxRun := func(cmd *Command, args []string) {
if cmd.Context() != ctx {
t.Errorf("Command %q must have context when called with ExecuteContext", cmd.Use)
}
}
rootCmd := &Command{Use: "root", Run: ctxRun, PreRun: ctxRun}
childCmd := &Command{Use: "child", Run: ctxRun, PreRun: ctxRun}
granchildCmd := &Command{Use: "grandchild", Run: ctxRun, PreRun: ctxRun}
childCmd.AddCommand(granchildCmd)
rootCmd.AddCommand(childCmd)
if _, _, err := executeCommandWithContextC(ctx, rootCmd, ""); err != nil {
t.Errorf("Root command must not fail: %+v", err)
}
if _, _, err := executeCommandWithContextC(ctx, rootCmd, "child"); err != nil {
t.Errorf("Subcommand must not fail: %+v", err)
}
if _, _, err := executeCommandWithContextC(ctx, rootCmd, "child", "grandchild"); err != nil {
t.Errorf("Command child must not fail: %+v", err)
}
}
func TestExecute_NoContext(t *testing.T) {
run := func(cmd *Command, args []string) {
if cmd.Context() != context.Background() {
t.Errorf("Command %s must have background context", cmd.Use)
}
}
rootCmd := &Command{Use: "root", Run: run, PreRun: run}
childCmd := &Command{Use: "child", Run: run, PreRun: run}
granchildCmd := &Command{Use: "grandchild", Run: run, PreRun: run}
childCmd.AddCommand(granchildCmd)
rootCmd.AddCommand(childCmd)
if _, err := executeCommand(rootCmd, ""); err != nil {
t.Errorf("Root command must not fail: %+v", err)
}
if _, err := executeCommand(rootCmd, "child"); err != nil {
t.Errorf("Subcommand must not fail: %+v", err)
}
if _, err := executeCommand(rootCmd, "child", "grandchild"); err != nil {
t.Errorf("Command child must not fail: %+v", err)
}
}
func TestRootUnknownCommandSilenced(t *testing.T) {
rootCmd := &Command{Use: "root", Run: emptyRun}
rootCmd.SilenceErrors = true
rootCmd.SilenceUsage = true
rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun})
output, _ := executeCommand(rootCmd, "unknown")
if output != "" {
t.Errorf("Expected blank output, because of silenced usage.\nGot:\n %q\n", output)
}
}
func TestCommandAlias(t *testing.T) {
var timesCmdArgs []string
rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}
echoCmd := &Command{
Use: "echo",
Aliases: []string{"say", "tell"},
Args: NoArgs,
Run: emptyRun,
}
timesCmd := &Command{
Use: "times",
Args: ExactArgs(2),
Run: func(_ *Command, args []string) { timesCmdArgs = args },
}
echoCmd.AddCommand(timesCmd)
rootCmd.AddCommand(echoCmd)
output, err := executeCommand(rootCmd, "tell", "times", "one", "two")
if output != "" {
t.Errorf("Unexpected output: %v", output)
}
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
got := strings.Join(timesCmdArgs, " ")
if got != onetwo {
t.Errorf("timesCmdArgs expected: %v, got: %v", onetwo, got)
}
}
func TestEnablePrefixMatching(t *testing.T) {
EnablePrefixMatching = true
var aCmdArgs []string
rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}
aCmd := &Command{
Use: "aCmd",
Args: ExactArgs(2),
Run: func(_ *Command, args []string) { aCmdArgs = args },
}
bCmd := &Command{Use: "bCmd", Args: NoArgs, Run: emptyRun}
rootCmd.AddCommand(aCmd, bCmd)
output, err := executeCommand(rootCmd, "a", "one", "two")
if output != "" {
t.Errorf("Unexpected output: %v", output)
}
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
got := strings.Join(aCmdArgs, " ")
if got != onetwo {
t.Errorf("aCmdArgs expected: %q, got: %q", onetwo, got)
}
EnablePrefixMatching = defaultPrefixMatching
}
func TestAliasPrefixMatching(t *testing.T) {
EnablePrefixMatching = true
var timesCmdArgs []string
rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}
echoCmd := &Command{
Use: "echo",
Aliases: []string{"say", "tell"},
Args: NoArgs,
Run: emptyRun,
}
timesCmd := &Command{
Use: "times",
Args: ExactArgs(2),
Run: func(_ *Command, args []string) { timesCmdArgs = args },
}
echoCmd.AddCommand(timesCmd)
rootCmd.AddCommand(echoCmd)
output, err := executeCommand(rootCmd, "sa", "times", "one", "two")
if output != "" {
t.Errorf("Unexpected output: %v", output)
}
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
got := strings.Join(timesCmdArgs, " ")
if got != onetwo {
t.Errorf("timesCmdArgs expected: %v, got: %v", onetwo, got)
}
EnablePrefixMatching = defaultPrefixMatching
}
// TestPlugin checks usage as plugin for another command such as kubectl. The
// executable is `kubectl-plugin`, but we run it as `kubectl plugin`. The help
// text should reflect the way we run the command.
func TestPlugin(t *testing.T) {
cmd := &Command{
Use: "kubectl-plugin",
Version: "1.0.0",
Args: NoArgs,
Annotations: map[string]string{
CommandDisplayNameAnnotation: "kubectl plugin",
},
Run: emptyRun,
}
cmdHelp, err := executeCommand(cmd, "-h")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
checkStringContains(t, cmdHelp, "kubectl plugin [flags]")
checkStringContains(t, cmdHelp, "help for kubectl plugin")
checkStringContains(t, cmdHelp, "version for kubectl plugin")
}
// TestPlugin checks usage as plugin with sub commands.
func TestPluginWithSubCommands(t *testing.T) {
rootCmd := &Command{
Use: "kubectl-plugin",
Version: "1.0.0",
Args: NoArgs,
Annotations: map[string]string{
CommandDisplayNameAnnotation: "kubectl plugin",
},
}
subCmd := &Command{Use: "sub [flags]", Args: NoArgs, Run: emptyRun}
rootCmd.AddCommand(subCmd)
rootHelp, err := executeCommand(rootCmd, "-h")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
checkStringContains(t, rootHelp, "kubectl plugin [command]")
checkStringContains(t, rootHelp, "help for kubectl plugin")
checkStringContains(t, rootHelp, "version for kubectl plugin")
checkStringContains(t, rootHelp, "kubectl plugin [command] --help")
childHelp, err := executeCommand(rootCmd, "sub", "-h")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
checkStringContains(t, childHelp, "kubectl plugin sub [flags]")
checkStringContains(t, childHelp, "help for sub")
helpHelp, err := executeCommand(rootCmd, "help", "-h")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
checkStringContains(t, helpHelp, "kubectl plugin help [path to command]")
checkStringContains(t, helpHelp, "kubectl plugin help [command]")
}
// TestChildSameName checks the correct behaviour of cobra in cases,
// when an application with name "foo" and with subcommand "foo"
// is executed with args "foo foo".
func TestChildSameName(t *testing.T) {
var fooCmdArgs []string
rootCmd := &Command{Use: "foo", Args: NoArgs, Run: emptyRun}
fooCmd := &Command{
Use: "foo",
Args: ExactArgs(2),
Run: func(_ *Command, args []string) { fooCmdArgs = args },
}
barCmd := &Command{Use: "bar", Args: NoArgs, Run: emptyRun}
rootCmd.AddCommand(fooCmd, barCmd)
output, err := executeCommand(rootCmd, "foo", "one", "two")
if output != "" {
t.Errorf("Unexpected output: %v", output)
}
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
got := strings.Join(fooCmdArgs, " ")
if got != onetwo {
t.Errorf("fooCmdArgs expected: %v, got: %v", onetwo, got)
}
}
// TestGrandChildSameName checks the correct behaviour of cobra in cases,
// when user has a root command and a grand child
// with the same name.
func TestGrandChildSameName(t *testing.T) {
var fooCmdArgs []string
rootCmd := &Command{Use: "foo", Args: NoArgs, Run: emptyRun}
barCmd := &Command{Use: "bar", Args: NoArgs, Run: emptyRun}
fooCmd := &Command{
Use: "foo",
Args: ExactArgs(2),
Run: func(_ *Command, args []string) { fooCmdArgs = args },
}
barCmd.AddCommand(fooCmd)
rootCmd.AddCommand(barCmd)
output, err := executeCommand(rootCmd, "bar", "foo", "one", "two")
if output != "" {
t.Errorf("Unexpected output: %v", output)
}
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
got := strings.Join(fooCmdArgs, " ")
if got != onetwo {
t.Errorf("fooCmdArgs expected: %v, got: %v", onetwo, got)
}
}
func TestFlagLong(t *testing.T) {
var cArgs []string
c := &Command{
Use: "c",
Args: ArbitraryArgs,
Run: func(_ *Command, args []string) { cArgs = args },
}
var intFlagValue int
var stringFlagValue string
c.Flags().IntVar(&intFlagValue, "intf", -1, "")
c.Flags().StringVar(&stringFlagValue, "sf", "", "")
output, err := executeCommand(c, "--intf=7", "--sf=abc", "one", "--", "two")
if output != "" {
t.Errorf("Unexpected output: %v", output)
}
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if c.ArgsLenAtDash() != 1 {
t.Errorf("Expected ArgsLenAtDash: %v but got %v", 1, c.ArgsLenAtDash())
}
if intFlagValue != 7 {
t.Errorf("Expected intFlagValue: %v, got %v", 7, intFlagValue)
}
if stringFlagValue != "abc" {
t.Errorf("Expected stringFlagValue: %q, got %q", "abc", stringFlagValue)
}
got := strings.Join(cArgs, " ")
if got != onetwo {
t.Errorf("rootCmdArgs expected: %q, got: %q", onetwo, got)
}
}
func TestFlagShort(t *testing.T) {
var cArgs []string
c := &Command{
Use: "c",
Args: ArbitraryArgs,
Run: func(_ *Command, args []string) { cArgs = args },
}
var intFlagValue int
var stringFlagValue string
c.Flags().IntVarP(&intFlagValue, "intf", "i", -1, "")
c.Flags().StringVarP(&stringFlagValue, "sf", "s", "", "")
output, err := executeCommand(c, "-i", "7", "-sabc", "one", "two")
if output != "" {
t.Errorf("Unexpected output: %v", output)
}
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if intFlagValue != 7 {
t.Errorf("Expected flag value: %v, got %v", 7, intFlagValue)
}
if stringFlagValue != "abc" {
t.Errorf("Expected stringFlagValue: %q, got %q", "abc", stringFlagValue)
}
got := strings.Join(cArgs, " ")
if got != onetwo {
t.Errorf("rootCmdArgs expected: %q, got: %q", onetwo, got)
}
}
func TestChildFlag(t *testing.T) {
rootCmd := &Command{Use: "root", Run: emptyRun}
childCmd := &Command{Use: "child", Run: emptyRun}
rootCmd.AddCommand(childCmd)
var intFlagValue int
childCmd.Flags().IntVarP(&intFlagValue, "intf", "i", -1, "")
output, err := executeCommand(rootCmd, "child", "-i7")
if output != "" {
t.Errorf("Unexpected output: %v", output)
}
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if intFlagValue != 7 {
t.Errorf("Expected flag value: %v, got %v", 7, intFlagValue)
}
}
func TestChildFlagWithParentLocalFlag(t *testing.T) {
rootCmd := &Command{Use: "root", Run: emptyRun}
childCmd := &Command{Use: "child", Run: emptyRun}
rootCmd.AddCommand(childCmd)
var intFlagValue int
rootCmd.Flags().StringP("sf", "s", "", "")
childCmd.Flags().IntVarP(&intFlagValue, "intf", "i", -1, "")
_, err := executeCommand(rootCmd, "child", "-i7", "-sabc")
if err == nil {
t.Errorf("Invalid flag should generate error")
}
checkStringContains(t, err.Error(), "unknown shorthand")
if intFlagValue != 7 {
t.Errorf("Expected flag value: %v, got %v", 7, intFlagValue)
}
}
func TestFlagInvalidInput(t *testing.T) {
rootCmd := &Command{Use: "root", Run: emptyRun}
rootCmd.Flags().IntP("intf", "i", -1, "")
_, err := executeCommand(rootCmd, "-iabc")
if err == nil {
t.Errorf("Invalid flag value should generate error")
}
checkStringContains(t, err.Error(), "invalid syntax")
}
func TestFlagBeforeCommand(t *testing.T) {
rootCmd := &Command{Use: "root", Run: emptyRun}
childCmd := &Command{Use: "child", Run: emptyRun}
rootCmd.AddCommand(childCmd)
var flagValue int
childCmd.Flags().IntVarP(&flagValue, "intf", "i", -1, "")
// With short flag.
_, err := executeCommand(rootCmd, "-i7", "child")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if flagValue != 7 {
t.Errorf("Expected flag value: %v, got %v", 7, flagValue)
}
// With long flag.
_, err = executeCommand(rootCmd, "--intf=8", "child")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if flagValue != 8 {
t.Errorf("Expected flag value: %v, got %v", 9, flagValue)
}
}
func TestStripFlags(t *testing.T) {
tests := []struct {
input []string
output []string
}{
{
[]string{"foo", "bar"},
[]string{"foo", "bar"},
},
{
[]string{"foo", "--str", "-s"},
[]string{"foo"},
},
{
[]string{"-s", "foo", "--str", "bar"},
[]string{},
},
{
[]string{"-i10", "echo"},
[]string{"echo"},
},
{
[]string{"-i=10", "echo"},
[]string{"echo"},
},
{
[]string{"--int=100", "echo"},
[]string{"echo"},
},
{
[]string{"-ib", "echo", "-sfoo", "baz"},
[]string{"echo", "baz"},
},
{
[]string{"-i=baz", "bar", "-i", "foo", "blah"},
[]string{"bar", "blah"},
},
{
[]string{"--int=baz", "-sbar", "-i", "foo", "blah"},
[]string{"blah"},
},
{
[]string{"--bool", "bar", "-i", "foo", "blah"},
[]string{"bar", "blah"},
},
{
[]string{"-b", "bar", "-i", "foo", "blah"},
[]string{"bar", "blah"},
},
{
[]string{"--persist", "bar"},
[]string{"bar"},
},
{
[]string{"-p", "bar"},
[]string{"bar"},
},
}
c := &Command{Use: "c", Run: emptyRun}
c.PersistentFlags().BoolP("persist", "p", false, "")
c.Flags().IntP("int", "i", -1, "")
c.Flags().StringP("str", "s", "", "")
c.Flags().BoolP("bool", "b", false, "")
for i, test := range tests {
got := stripFlags(test.input, c)
if !reflect.DeepEqual(test.output, got) {
t.Errorf("(%v) Expected: %v, got: %v", i, test.output, got)
}
}
}
func TestDisableFlagParsing(t *testing.T) {
var cArgs []string
c := &Command{
Use: "c",
DisableFlagParsing: true,
Run: func(_ *Command, args []string) {
cArgs = args
},
}
args := []string{"cmd", "-v", "-race", "-file", "foo.go"}
output, err := executeCommand(c, args...)
if output != "" {
t.Errorf("Unexpected output: %v", output)
}
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if !reflect.DeepEqual(args, cArgs) {
t.Errorf("Expected: %v, got: %v", args, cArgs)
}
}
func TestPersistentFlagsOnSameCommand(t *testing.T) {
var rootCmdArgs []string
rootCmd := &Command{
Use: "root",
Args: ArbitraryArgs,
Run: func(_ *Command, args []string) { rootCmdArgs = args },
}
var flagValue int
rootCmd.PersistentFlags().IntVarP(&flagValue, "intf", "i", -1, "")
output, err := executeCommand(rootCmd, "-i7", "one", "two")
if output != "" {
t.Errorf("Unexpected output: %v", output)
}
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
got := strings.Join(rootCmdArgs, " ")
if got != onetwo {
t.Errorf("rootCmdArgs expected: %q, got %q", onetwo, got)
}
if flagValue != 7 {
t.Errorf("flagValue expected: %v, got %v", 7, flagValue)
}
}
// TestEmptyInputs checks,
// if flags correctly parsed with blank strings in args.
func TestEmptyInputs(t *testing.T) {
c := &Command{Use: "c", Run: emptyRun}
var flagValue int
c.Flags().IntVarP(&flagValue, "intf", "i", -1, "")
output, err := executeCommand(c, "", "-i7", "")
if output != "" {
t.Errorf("Unexpected output: %v", output)
}
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if flagValue != 7 {
t.Errorf("flagValue expected: %v, got %v", 7, flagValue)
}
}
func TestChildFlagShadowsParentPersistentFlag(t *testing.T) {
parent := &Command{Use: "parent", Run: emptyRun}
child := &Command{Use: "child", Run: emptyRun}
parent.PersistentFlags().Bool("boolf", false, "")
parent.PersistentFlags().Int("intf", -1, "")
child.Flags().String("strf", "", "")
child.Flags().Int("intf", -1, "")
parent.AddCommand(child)
childInherited := child.InheritedFlags()
childLocal := child.LocalFlags()
if childLocal.Lookup("strf") == nil {
t.Error(`LocalFlags expected to contain "strf", got "nil"`)
}
if childInherited.Lookup("boolf") == nil {
t.Error(`InheritedFlags expected to contain "boolf", got "nil"`)
}
if childInherited.Lookup("intf") != nil {
t.Errorf(`InheritedFlags should not contain shadowed flag "intf"`)
}
if childLocal.Lookup("intf") == nil {
t.Error(`LocalFlags expected to contain "intf", got "nil"`)
}
}
func TestPersistentFlagsOnChild(t *testing.T) {
var childCmdArgs []string
rootCmd := &Command{Use: "root", Run: emptyRun}
childCmd := &Command{
Use: "child",
Args: ArbitraryArgs,
Run: func(_ *Command, args []string) { childCmdArgs = args },
}
rootCmd.AddCommand(childCmd)
var parentFlagValue int
var childFlagValue int
rootCmd.PersistentFlags().IntVarP(&parentFlagValue, "parentf", "p", -1, "")
childCmd.Flags().IntVarP(&childFlagValue, "childf", "c", -1, "")
output, err := executeCommand(rootCmd, "child", "-c7", "-p8", "one", "two")
if output != "" {
t.Errorf("Unexpected output: %v", output)
}
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
got := strings.Join(childCmdArgs, " ")
if got != onetwo {
t.Errorf("rootCmdArgs expected: %q, got: %q", onetwo, got)
}
if parentFlagValue != 8 {
t.Errorf("parentFlagValue expected: %v, got %v", 8, parentFlagValue)
}
if childFlagValue != 7 {
t.Errorf("childFlagValue expected: %v, got %v", 7, childFlagValue)
}
}
func TestRequiredFlags(t *testing.T) {
c := &Command{Use: "c", Run: emptyRun}
c.Flags().String("foo1", "", "")
assertNoErr(t, c.MarkFlagRequired("foo1"))
c.Flags().String("foo2", "", "")
assertNoErr(t, c.MarkFlagRequired("foo2"))
c.Flags().String("bar", "", "")
expected := fmt.Sprintf("required flag(s) %q, %q not set", "foo1", "foo2")
_, err := executeCommand(c)
got := err.Error()
if got != expected {
t.Errorf("Expected error: %q, got: %q", expected, got)
}
}
func TestPersistentRequiredFlags(t *testing.T) {
parent := &Command{Use: "parent", Run: emptyRun}
parent.PersistentFlags().String("foo1", "", "")
assertNoErr(t, parent.MarkPersistentFlagRequired("foo1"))
parent.PersistentFlags().String("foo2", "", "")
assertNoErr(t, parent.MarkPersistentFlagRequired("foo2"))
parent.Flags().String("foo3", "", "")
child := &Command{Use: "child", Run: emptyRun}
child.Flags().String("bar1", "", "")
assertNoErr(t, child.MarkFlagRequired("bar1"))
child.Flags().String("bar2", "", "")
assertNoErr(t, child.MarkFlagRequired("bar2"))
child.Flags().String("bar3", "", "")
parent.AddCommand(child)
expected := fmt.Sprintf("required flag(s) %q, %q, %q, %q not set", "bar1", "bar2", "foo1", "foo2")
_, err := executeCommand(parent, "child")
if err.Error() != expected {
t.Errorf("Expected %q, got %q", expected, err.Error())
}
}
func TestPersistentRequiredFlagsWithDisableFlagParsing(t *testing.T) {
// Make sure a required persistent flag does not break
// commands that disable flag parsing
parent := &Command{Use: "parent", Run: emptyRun}
parent.PersistentFlags().Bool("foo", false, "")
flag := parent.PersistentFlags().Lookup("foo")
assertNoErr(t, parent.MarkPersistentFlagRequired("foo"))
child := &Command{Use: "child", Run: emptyRun}
child.DisableFlagParsing = true
parent.AddCommand(child)
if _, err := executeCommand(parent, "--foo", "child"); err != nil {
t.Errorf("Unexpected error: %v", err)
}
// Reset the flag or else it will remember the state from the previous command
flag.Changed = false
if _, err := executeCommand(parent, "child", "--foo"); err != nil {
t.Errorf("Unexpected error: %v", err)
}
// Reset the flag or else it will remember the state from the previous command
flag.Changed = false
if _, err := executeCommand(parent, "child"); err != nil {
t.Errorf("Unexpected error: %v", err)
}
}
func TestInitHelpFlagMergesFlags(t *testing.T) {
usage := "custom flag"
rootCmd := &Command{Use: "root"}
rootCmd.PersistentFlags().Bool("help", false, "custom flag")
childCmd := &Command{Use: "child"}
rootCmd.AddCommand(childCmd)
childCmd.InitDefaultHelpFlag()
got := childCmd.Flags().Lookup("help").Usage
if got != usage {
t.Errorf("Expected the help flag from the root command with usage: %v\nGot the default with usage: %v", usage, got)
}
}
func TestHelpCommandExecuted(t *testing.T) {
rootCmd := &Command{Use: "root", Long: "Long description", Run: emptyRun}
rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun})
output, err := executeCommand(rootCmd, "help")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
checkStringContains(t, output, rootCmd.Long)
}
func TestHelpCommandExecutedOnChild(t *testing.T) {
rootCmd := &Command{Use: "root", Run: emptyRun}
childCmd := &Command{Use: "child", Long: "Long description", Run: emptyRun}
rootCmd.AddCommand(childCmd)
output, err := executeCommand(rootCmd, "help", "child")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
checkStringContains(t, output, childCmd.Long)
}
func TestHelpCommandExecutedOnChildWithFlagThatShadowsParentFlag(t *testing.T) {
parent := &Command{Use: "parent", Run: emptyRun}
child := &Command{Use: "child", Run: emptyRun}
parent.AddCommand(child)
parent.PersistentFlags().Bool("foo", false, "parent foo usage")
parent.PersistentFlags().Bool("bar", false, "parent bar usage")
child.Flags().Bool("foo", false, "child foo usage") // This shadows parent's foo flag
child.Flags().Bool("baz", false, "child baz usage")
got, err := executeCommand(parent, "help", "child")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
expected := `Usage:
parent child [flags]
Flags:
--baz child baz usage
--foo child foo usage
-h, --help help for child
Global Flags:
--bar parent bar usage
`
if got != expected {
t.Errorf("Help text mismatch.\nExpected:\n%s\n\nGot:\n%s\n", expected, got)
}
}
func TestSetHelpCommand(t *testing.T) {
c := &Command{Use: "c", Run: emptyRun}
c.AddCommand(&Command{Use: "empty", Run: emptyRun})