summaryrefslogtreecommitdiffstats
path: root/vendor/github.com/spf13/cobra/cobra_test.go
blob: d5df951e677f47aad185242cd43021df421e8b83 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
package cobra

import (
	"bytes"
	"fmt"
	"os"
	"reflect"
	"runtime"
	"strings"
	"testing"
	"text/template"

	"github.com/spf13/pflag"
)

var tp, te, tt, tr []string
var rootPersPre, echoPre, echoPersPre, timesPersPre []string
var flagb1, flagb2, flagb3, flagbr, flagbp bool
var flags1, flags2a, flags2b, flags3, outs string
var flagi1, flagi2, flagi3, flagi4, flagir int
var rootcalled bool
var versionUsed int

const strtwoParentHelp = "help message for parent flag strtwo"
const strtwoChildHelp = "help message for child flag strtwo"

var cmdHidden = &Command{
	Use:   "hide [secret string to print]",
	Short: "Print anything to screen (if command is known)",
	Long:  `an absolutely utterly useless command for testing.`,
	Run: func(cmd *Command, args []string) {
		outs = "hidden"
	},
	Hidden: true,
}

var cmdPrint = &Command{
	Use:   "print [string to print]",
	Args:  MinimumNArgs(1),
	Short: "Print anything to the screen",
	Long:  `an absolutely utterly useless command for testing.`,
	Run: func(cmd *Command, args []string) {
		tp = args
	},
}

var cmdEcho = &Command{
	Use:     "echo [string to echo]",
	Aliases: []string{"say"},
	Short:   "Echo anything to the screen",
	Long:    `an utterly useless command for testing.`,
	Example: "Just run cobra-test echo",
	PersistentPreRun: func(cmd *Command, args []string) {
		echoPersPre = args
	},
	PreRun: func(cmd *Command, args []string) {
		echoPre = args
	},
	Run: func(cmd *Command, args []string) {
		te = args
	},
}

var cmdEchoSub = &Command{
	Use:   "echosub [string to print]",
	Short: "second sub command for echo",
	Long:  `an absolutely utterly useless command for testing gendocs!.`,
	Run: func(cmd *Command, args []string) {
	},
}

var cmdDeprecated = &Command{
	Use:        "deprecated [can't do anything here]",
	Short:      "A command which is deprecated",
	Long:       `an absolutely utterly useless command for testing deprecation!.`,
	Deprecated: "Please use echo instead",
	Run: func(cmd *Command, args []string) {
	},
	Args: NoArgs,
}

var cmdTimes = &Command{
	Use:        "times [# times] [string to echo]",
	SuggestFor: []string{"counts"},
	Short:      "Echo anything to the screen more times",
	Long:       `a slightly useless command for testing.`,
	PersistentPreRun: func(cmd *Command, args []string) {
		timesPersPre = args
	},
	Run: func(cmd *Command, args []string) {
		tt = args
	},
	Args:      OnlyValidArgs,
	ValidArgs: []string{"one", "two", "three", "four"},
}

var cmdRootNoRun = &Command{
	Use:   "cobra-test",
	Short: "The root can run its own function",
	Long:  "The root description for help",
	PersistentPreRun: func(cmd *Command, args []string) {
		rootPersPre = args
	},
}

var cmdRootSameName = &Command{
	Use:   "print",
	Short: "Root with the same name as a subcommand",
	Long:  "The root description for help",
}

var cmdRootTakesArgs = &Command{
	Use:   "root-with-args [random args]",
	Short: "The root can run it's own function and takes args!",
	Long:  "The root description for help, and some args",
	Run: func(cmd *Command, args []string) {
		tr = args
	},
	Args: ArbitraryArgs,
}

var cmdRootWithRun = &Command{
	Use:   "cobra-test",
	Short: "The root can run its own function",
	Long:  "The root description for help",
	Run: func(cmd *Command, args []string) {
		tr = args
		rootcalled = true
	},
}

var cmdSubNoRun = &Command{
	Use:   "subnorun",
	Short: "A subcommand without a Run function",
	Long:  "A long output about a subcommand without a Run function",
}

var cmdCustomFlags = &Command{
	Use:   "customflags [flags] -- REMOTE_COMMAND",
	Short: "A command that expects flags in a custom location",
	Long:  "A long output about a command that expects flags in a custom location",
	Run: func(cmd *Command, args []string) {
	},
}

var cmdVersion1 = &Command{
	Use:   "version",
	Short: "Print the version number",
	Long:  `First version of the version command`,
	Run: func(cmd *Command, args []string) {
		versionUsed = 1
	},
}

var cmdVersion2 = &Command{
	Use:   "version",
	Short: "Print the version number",
	Long:  `Second version of the version command`,
	Run: func(cmd *Command, args []string) {
		versionUsed = 2
	},
}

var cmdColon = &Command{
	Use: "cmd:colon",
	Run: func(cmd *Command, args []string) {
	},
}

func flagInit() {
	cmdEcho.ResetFlags()
	cmdPrint.ResetFlags()
	cmdTimes.ResetFlags()
	cmdRootNoRun.ResetFlags()
	cmdRootSameName.ResetFlags()
	cmdRootWithRun.ResetFlags()
	cmdSubNoRun.ResetFlags()
	cmdCustomFlags.ResetFlags()
	cmdVersion1.ResetFlags()
	cmdVersion2.ResetFlags()

	cmdRootNoRun.PersistentFlags().StringVarP(&flags2a, "strtwo", "t", "two", strtwoParentHelp)
	cmdCustomFlags.Flags().IntVar(&flagi4, "intfour", 456, "help message for flag intfour")
	cmdEcho.Flags().BoolVarP(&flagb1, "boolone", "b", true, "help message for flag boolone")
	cmdEcho.Flags().IntVarP(&flagi1, "intone", "i", 123, "help message for flag intone")
	cmdEcho.PersistentFlags().BoolVarP(&flagbp, "persistentbool", "p", false, "help message for flag persistentbool")
	cmdEcho.PersistentFlags().StringVarP(&flags1, "strone", "s", "one", "help message for flag strone")
	cmdPrint.Flags().IntVarP(&flagi3, "intthree", "i", 345, "help message for flag intthree")
	cmdTimes.Flags().BoolVarP(&flagb2, "booltwo", "c", false, "help message for flag booltwo")
	cmdTimes.Flags().IntVarP(&flagi2, "inttwo", "j", 234, "help message for flag inttwo")
	cmdTimes.Flags().StringVarP(&flags2b, "strtwo", "t", "2", strtwoChildHelp)
	cmdTimes.PersistentFlags().StringVarP(&flags2b, "strtwo", "t", "2", strtwoChildHelp)
	cmdPrint.Flags().BoolVarP(&flagb3, "boolthree", "b", true, "help message for flag boolthree")
	cmdPrint.PersistentFlags().StringVarP(&flags3, "strthree", "s", "three", "help message for flag strthree")
}

func commandInit() {
	cmdEcho.ResetCommands()
	cmdPrint.ResetCommands()
	cmdTimes.ResetCommands()
	cmdRootNoRun.ResetCommands()
	cmdRootSameName.ResetCommands()
	cmdRootWithRun.ResetCommands()
	cmdSubNoRun.ResetCommands()
	cmdCustomFlags.ResetCommands()
}

func initialize() *Command {
	tt, tp, te = nil, nil, nil
	rootPersPre, echoPre, echoPersPre, timesPersPre = nil, nil, nil, nil

	var c = cmdRootNoRun
	flagInit()
	commandInit()
	return c
}

func initializeWithSameName() *Command {
	tt, tp, te = nil, nil, nil
	rootPersPre, echoPre, echoPersPre, timesPersPre = nil, nil, nil, nil
	var c = cmdRootSameName
	flagInit()
	commandInit()
	return c
}

func initializeWithRootCmd() *Command {
	cmdRootWithRun.ResetCommands()
	tt, tp, te, tr, rootcalled = nil, nil, nil, nil, false
	flagInit()
	cmdRootWithRun.Flags().BoolVarP(&flagbr, "boolroot", "b", false, "help message for flag boolroot")
	cmdRootWithRun.Flags().IntVarP(&flagir, "introot", "i", 321, "help message for flag introot")
	commandInit()
	return cmdRootWithRun
}

type resulter struct {
	Error   error
	Output  string
	Command *Command
}

func fullSetupTest(args ...string) resulter {
	c := initializeWithRootCmd()

	return fullTester(c, args...)
}

func noRRSetupTestSilenced(args ...string) resulter {
	c := initialize()
	c.SilenceErrors = true
	c.SilenceUsage = true
	return fullTester(c, args...)
}

func noRRSetupTest(args ...string) resulter {
	c := initialize()

	return fullTester(c, args...)
}

func rootOnlySetupTest(args ...string) resulter {
	c := initializeWithRootCmd()

	return simpleTester(c, args...)
}

func simpleTester(c *Command, args ...string) resulter {
	buf := new(bytes.Buffer)
	// Testing flag with invalid input
	c.SetOutput(buf)
	c.SetArgs(args)

	err := c.Execute()
	output := buf.String()

	return resulter{err, output, c}
}

func simpleTesterC(c *Command, args ...string) resulter {
	buf := new(bytes.Buffer)
	// Testing flag with invalid input
	c.SetOutput(buf)
	c.SetArgs(args)

	cmd, err := c.ExecuteC()
	output := buf.String()

	return resulter{err, output, cmd}
}

func fullTester(c *Command, args ...string) resulter {
	buf := new(bytes.Buffer)
	// Testing flag with invalid input
	c.SetOutput(buf)
	cmdEcho.AddCommand(cmdTimes)
	c.AddCommand(cmdPrint, cmdEcho, cmdSubNoRun, cmdCustomFlags, cmdDeprecated)
	c.SetArgs(args)

	err := c.Execute()
	output := buf.String()

	return resulter{err, output, c}
}

func logErr(t *testing.T, found, expected string) {
	out := new(bytes.Buffer)

	_, _, line, ok := runtime.Caller(2)
	if ok {
		fmt.Fprintf(out, "Line: %d ", line)
	}
	fmt.Fprintf(out, "Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
	t.Errorf(out.String())
}

func checkStringContains(t *testing.T, found, expected string) {
	if !strings.Contains(found, expected) {
		logErr(t, found, expected)
	}
}

func checkResultContains(t *testing.T, x resulter, check string) {
	checkStringContains(t, x.Output, check)
}

func checkStringOmits(t *testing.T, found, expected string) {
	if strings.Contains(found, expected) {
		logErr(t, found, expected)
	}
}

func checkResultOmits(t *testing.T, x resulter, check string) {
	checkStringOmits(t, x.Output, check)
}

func checkOutputContains(t *testing.T, c *Command, check string) {
	buf := new(bytes.Buffer)
	c.SetOutput(buf)
	c.Execute()

	if !strings.Contains(buf.String(), check) {
		logErr(t, buf.String(), check)
	}
}

func TestSingleCommand(t *testing.T) {
	noRRSetupTest("print", "one", "two")

	if te != nil || tt != nil {
		t.Error("Wrong command called")
	}
	if tp == nil {
		t.Error("Wrong command called")
	}
	if strings.Join(tp, " ") != "one two" {
		t.Error("Command didn't parse correctly")
	}
}

func TestChildCommand(t *testing.T) {
	noRRSetupTest("echo", "times", "one", "two")

	if te != nil || tp != nil {
		t.Error("Wrong command called")
	}
	if tt == nil {
		t.Error("Wrong command called")
	}
	if strings.Join(tt, " ") != "one two" {
		t.Error("Command didn't parse correctly")
	}
}

func TestCommandAlias(t *testing.T) {
	noRRSetupTest("say", "times", "one", "two")

	if te != nil || tp != nil {
		t.Error("Wrong command called")
	}
	if tt == nil {
		t.Error("Wrong command called")
	}
	if strings.Join(tt, " ") != "one two" {
		t.Error("Command didn't parse correctly")
	}
}

func TestPrefixMatching(t *testing.T) {
	EnablePrefixMatching = true
	noRRSetupTest("ech", "times", "one", "two")

	if te != nil || tp != nil {
		t.Error("Wrong command called")
	}
	if tt == nil {
		t.Error("Wrong command called")
	}
	if strings.Join(tt, " ") != "one two" {
		t.Error("Command didn't parse correctly")
	}

	EnablePrefixMatching = false
}

func TestNoPrefixMatching(t *testing.T) {
	EnablePrefixMatching = false

	noRRSetupTest("ech", "times", "one", "two")

	if !(tt == nil && te == nil && tp == nil) {
		t.Error("Wrong command called")
	}
}

func TestAliasPrefixMatching(t *testing.T) {
	EnablePrefixMatching = true
	noRRSetupTest("sa", "times", "one", "two")

	if te != nil || tp != nil {
		t.Error("Wrong command called")
	}
	if tt == nil {
		t.Error("Wrong command called")
	}
	if strings.Join(tt, " ") != "one two" {
		t.Error("Command didn't parse correctly")
	}
	EnablePrefixMatching = false
}

func TestChildSameName(t *testing.T) {
	c := initializeWithSameName()
	c.AddCommand(cmdPrint, cmdEcho)
	c.SetArgs([]string{"print", "one", "two"})
	c.Execute()

	if te != nil || tt != nil {
		t.Error("Wrong command called")
	}
	if tp == nil {
		t.Error("Wrong command called")
	}
	if strings.Join(tp, " ") != "one two" {
		t.Error("Command didn't parse correctly")
	}
}

func TestGrandChildSameName(t *testing.T) {
	c := initializeWithSameName()
	cmdTimes.AddCommand(cmdPrint)
	c.AddCommand(cmdTimes)
	c.SetArgs([]string{"times", "print", "one", "two"})
	c.Execute()

	if te != nil || tt != nil {
		t.Error("Wrong command called")
	}
	if tp == nil {
		t.Error("Wrong command called")
	}
	if strings.Join(tp, " ") != "one two" {
		t.Error("Command didn't parse correctly")
	}
}

func TestUsage(t *testing.T) {
	x := fullSetupTest("help")
	checkResultContains(t, x, cmdRootWithRun.Use+" [flags]")
	x = fullSetupTest("help", "customflags")
	checkResultContains(t, x, cmdCustomFlags.Use)
	checkResultOmits(t, x, cmdCustomFlags.Use+" [flags]")
}

func TestRootTakesNoArgs(t *testing.T) {
	c := initializeWithSameName()
	c.AddCommand(cmdPrint, cmdEcho)
	result := simpleTester(c, "illegal")

	if result.Error == nil {
		t.Fatal("Expected an error")
	}

	expectedError := `unknown command "illegal" for "print"`
	if !strings.Contains(result.Error.Error(), expectedError) {
		t.Errorf("exptected %v, got %v", expectedError, result.Error.Error())
	}
}

func TestRootTakesArgs(t *testing.T) {
	c := cmdRootTakesArgs
	result := simpleTester(c, "legal")

	if result.Error != nil {
		t.Errorf("expected no error, but got %v", result.Error)
	}
}

func TestSubCmdTakesNoArgs(t *testing.T) {
	result := fullSetupTest("deprecated", "illegal")

	if result.Error == nil {
		t.Fatal("Expected an error")
	}

	expectedError := `unknown command "illegal" for "cobra-test deprecated"`
	if !strings.Contains(result.Error.Error(), expectedError) {
		t.Errorf("expected %v, got %v", expectedError, result.Error.Error())
	}
}

func TestSubCmdTakesArgs(t *testing.T) {
	noRRSetupTest("echo", "times", "one", "two")
	if strings.Join(tt, " ") != "one two" {
		t.Error("Command didn't parse correctly")
	}
}

func TestCmdOnlyValidArgs(t *testing.T) {
	result := noRRSetupTest("echo", "times", "one", "two", "five")

	if result.Error == nil {
		t.Fatal("Expected an error")
	}

	expectedError := `invalid argument "five"`
	if !strings.Contains(result.Error.Error(), expectedError) {
		t.Errorf("expected %v, got %v", expectedError, result.Error.Error())
	}
}

func TestFlagLong(t *testing.T) {
	noRRSetupTest("echo", "--intone=13", "something", "--", "here")

	if cmdEcho.ArgsLenAtDash() != 1 {
		t.Errorf("expected argsLenAtDash: %d but got %d", 1, cmdRootNoRun.ArgsLenAtDash())
	}
	if strings.Join(te, " ") != "something here" {
		t.Errorf("flags didn't leave proper args remaining..%s given", te)
	}
	if flagi1 != 13 {
		t.Errorf("int flag didn't get correct value, had %d", flagi1)
	}
	if flagi2 != 234 {
		t.Errorf("default flag value changed, 234 expected, %d given", flagi2)
	}
}

func TestFlagShort(t *testing.T) {
	noRRSetupTest("echo", "-i13", "--", "something", "here")

	if cmdEcho.ArgsLenAtDash() != 0 {
		t.Errorf("expected argsLenAtDash: %d but got %d", 0, cmdRootNoRun.ArgsLenAtDash())
	}
	if strings.Join(te, " ") != "something here" {
		t.Errorf("flags didn't leave proper args remaining..%s given", te)
	}
	if flagi1 != 13 {
		t.Errorf("int flag didn't get correct value, had %d", flagi1)
	}
	if flagi2 != 234 {
		t.Errorf("default flag value changed, 234 expected, %d given", flagi2)
	}

	noRRSetupTest("echo", "-i", "13", "something", "here")

	if strings.Join(te, " ") != "something here" {
		t.Errorf("flags didn't leave proper args remaining..%s given", te)
	}
	if flagi1 != 13 {
		t.Errorf("int flag didn't get correct value, had %d", flagi1)
	}
	if flagi2 != 234 {
		t.Errorf("default flag value changed, 234 expected, %d given", flagi2)
	}

	noRRSetupTest("print", "-i99", "one", "two")

	if strings.Join(tp, " ") != "one two" {
		t.Errorf("flags didn't leave proper args remaining..%s given", tp)
	}
	if flagi3 != 99 {
		t.Errorf("int flag didn't get correct value, had %d", flagi3)
	}
	if flagi1 != 123 {
		t.Errorf("default flag value changed on different command with same shortname, 234 expected, %d given", flagi2)
	}
}

func TestChildCommandFlags(t *testing.T) {
	noRRSetupTest("echo", "times", "-j", "99", "one", "two")

	if strings.Join(tt, " ") != "one two" {
		t.Errorf("flags didn't leave proper args remaining..%s given", tt)
	}

	// Testing with flag that shouldn't be persistent
	r := noRRSetupTest("echo", "times", "-j", "99", "-i77", "one", "two")

	if r.Error == nil {
		t.Errorf("invalid flag should generate error")
	}

	if !strings.Contains(r.Error.Error(), "unknown shorthand") {
		t.Errorf("Wrong error message displayed, \n %s", r.Error)
	}

	if flagi2 != 99 {
		t.Errorf("flag value should be 99, %d given", flagi2)
	}

	if flagi1 != 123 {
		t.Errorf("unset flag should have default value, expecting 123, given %d", flagi1)
	}

	// Testing with flag only existing on child
	r = noRRSetupTest("echo", "-j", "99", "-i77", "one", "two")

	if r.Error == nil {
		t.Errorf("invalid flag should generate error")
	}
	if !strings.Contains(r.Error.Error(), "unknown shorthand flag") {
		t.Errorf("Wrong error message displayed, \n %s", r.Error)
	}

	// Testing with persistent flag overwritten by child
	noRRSetupTest("echo", "times", "--strtwo=child", "one", "two")

	if flags2b != "child" {
		t.Errorf("flag value should be child, %s given", flags2b)
	}

	if flags2a != "two" {
		t.Errorf("unset flag should have default value, expecting two, given %s", flags2a)
	}

	// Testing flag with invalid input
	r = noRRSetupTest("echo", "-i10E")

	if r.Error == nil {
		t.Errorf("invalid input should generate error")
	}
	if !strings.Contains(r.Error.Error(), "invalid syntax") {
		t.Errorf("Wrong error message displayed, \n %s", r.Error)
	}
}

func TestTrailingCommandFlags(t *testing.T) {
	x := fullSetupTest("echo", "two", "-x")

	if x.Error == nil {
		t.Errorf("invalid flag should generate error")
	}
}

func TestInvalidSubcommandFlags(t *testing.T) {
	cmd := initializeWithRootCmd()
	cmd.AddCommand(cmdTimes)

	result := simpleTester(cmd, "times", "--inttwo=2", "--badflag=bar")
	// given that we are not checking here result.Error we check for
	// stock usage message
	checkResultContains(t, result, "cobra-test times [# times]")
	if strings.Contains(result.Error.Error(), "unknown flag: --inttwo") {
		t.Errorf("invalid --badflag flag shouldn't fail on 'unknown' --inttwo flag")
	}

}

func TestSubcommandExecuteC(t *testing.T) {
	cmd := initializeWithRootCmd()
	double := &Command{
		Use: "double message",
		Run: func(c *Command, args []string) {
			msg := strings.Join(args, " ")
			c.Println(msg, msg)
		},
	}

	echo := &Command{
		Use: "echo message",
		Run: func(c *Command, args []string) {
			msg := strings.Join(args, " ")
			c.Println(msg)
		},
	}

	cmd.AddCommand(double, echo)

	result := simpleTesterC(cmd, "double", "hello", "world")
	checkResultContains(t, result, "hello world hello world")

	if result.Command.Name() != "double" {
		t.Errorf("invalid cmd returned from ExecuteC: should be 'double' but got %s", result.Command.Name())
	}

	result = simpleTesterC(cmd, "echo", "msg", "to", "be", "echoed")
	checkResultContains(t, result, "msg to be echoed")

	if result.Command.Name() != "echo" {
		t.Errorf("invalid cmd returned from ExecuteC: should be 'echo' but got %s", result.Command.Name())
	}
}

func TestSubcommandArgEvaluation(t *testing.T) {
	cmd := initializeWithRootCmd()

	first := &Command{
		Use: "first",
		Run: func(cmd *Command, args []string) {
		},
	}
	cmd.AddCommand(first)

	second := &Command{
		Use: "second",
		Run: func(cmd *Command, args []string) {
			fmt.Fprintf(cmd.OutOrStdout(), "%v", args)
		},
	}
	first.AddCommand(second)

	result := simpleTester(cmd, "first", "second", "first", "third")

	expectedOutput := fmt.Sprint([]string{"first third"})
	if result.Output != expectedOutput {
		t.Errorf("exptected %v, got %v", expectedOutput, result.Output)
	}
}

func TestPersistentFlags(t *testing.T) {
	fullSetupTest("echo", "-s", "something", "-p", "more", "here")

	// persistentFlag should act like normal flag on its own command
	if strings.Join(te, " ") != "more here" {
		t.Errorf("flags didn't leave proper args remaining..%s given", te)
	}
	if flags1 != "something" {
		t.Errorf("string flag didn't get correct value, had %v", flags1)
	}
	if !flagbp {
		t.Errorf("persistent bool flag not parsed correctly. Expected true, had %v", flagbp)
	}

	// persistentFlag should act like normal flag on its own command
	fullSetupTest("echo", "times", "-s", "again", "-c", "-p", "one", "two")

	if strings.Join(tt, " ") != "one two" {
		t.Errorf("flags didn't leave proper args remaining. %s given", tt)
	}

	if flags1 != "again" {
		t.Errorf("string flag didn't get correct value, had %v", flags1)
	}

	if !flagb2 {
		t.Errorf("local flag not parsed correctly. Expected true, had %v", flagb2)
	}
	if !flagbp {
		t.Errorf("persistent bool flag not parsed correctly. Expected true, had %v", flagbp)
	}
}

func TestHelpCommand(t *testing.T) {
	x := fullSetupTest("help")
	checkResultContains(t, x, cmdRootWithRun.Long)

	x = fullSetupTest("help", "echo")
	checkResultContains(t, x, cmdEcho.Long)

	x = fullSetupTest("help", "echo", "times")
	checkResultContains(t, x, cmdTimes.Long)
}

func TestChildCommandHelp(t *testing.T) {
	c := noRRSetupTest("print", "--help")
	checkResultContains(t, c, strtwoParentHelp)
	r := noRRSetupTest("echo", "times", "--help")
	checkResultContains(t, r, strtwoChildHelp)
}

func TestNonRunChildHelp(t *testing.T) {
	x := noRRSetupTest("subnorun")
	checkResultContains(t, x, cmdSubNoRun.Long)
}

func TestRunnableRootCommand(t *testing.T) {
	x := fullSetupTest("")

	if !rootcalled {
		t.Errorf("Root Function was not called\n out:%v", x.Error)
	}
}

func TestVisitParents(t *testing.T) {
	c := &Command{Use: "app"}
	sub := &Command{Use: "sub"}
	dsub := &Command{Use: "dsub"}
	sub.AddCommand(dsub)
	c.AddCommand(sub)
	total := 0
	add := func(x *Command) {
		total++
	}
	sub.VisitParents(add)
	if total != 1 {
		t.Errorf("Should have visited 1 parent but visited %d", total)
	}

	total = 0
	dsub.VisitParents(add)
	if total != 2 {
		t.Errorf("Should have visited 2 parent but visited %d", total)
	}

	total = 0
	c.VisitParents(add)
	if total != 0 {
		t.Errorf("Should have not visited any parent but visited %d", total)
	}
}

func TestRunnableRootCommandNilInput(t *testing.T) {
	c := initializeWithRootCmd()

	buf := new(bytes.Buffer)
	// Testing flag with invalid input
	c.SetOutput(buf)
	cmdEcho.AddCommand(cmdTimes)
	c.AddCommand(cmdPrint, cmdEcho)
	c.SetArgs([]string{})

	err := c.Execute()
	if err != nil {
		t.Errorf("Execute() failed with %v", err)
	}

	if !rootcalled {
		t.Errorf("Root Function was not called")
	}
}

func TestRunnableRootCommandEmptyInput(t *testing.T) {
	args := []string{"", "--introot=12", ""}
	c := initializeWithRootCmd()

	buf := new(bytes.Buffer)
	// Testing flag with invalid input
	c.SetOutput(buf)
	cmdEcho.AddCommand(cmdTimes)
	c.AddCommand(cmdPrint, cmdEcho)
	c.SetArgs(args)

	c.Execute()

	if !rootcalled {
		t.Errorf("Root Function was not called.\nOutput was:\n%s\n", buf)
	}
}

func TestInvalidSubcommandWhenArgsAllowed(t *testing.T) {
	fullSetupTest("echo", "invalid-sub")

	if te[0] != "invalid-sub" {
		t.Errorf("Subcommand didn't work...")
	}
}

func TestRootFlags(t *testing.T) {
	fullSetupTest("-i", "17", "-b")

	if !flagbr {
		t.Errorf("flag value should be true, %v given", flagbr)
	}

	if flagir != 17 {
		t.Errorf("flag value should be 17, %d given", flagir)
	}
}

func TestRootHelp(t *testing.T) {
	x := fullSetupTest("--help")

	checkResultContains(t, x, "Available Commands:")
	checkResultContains(t, x, "for more information about a command")

	if strings.Contains(x.Output, "unknown flag: --help") {
		t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output)
	}

	if strings.Contains(x.Output, cmdEcho.Use) {
		t.Errorf("--help shouldn't display subcommand's usage, Got: \n %s", x.Output)
	}

	x = fullSetupTest("echo", "--help")

	if strings.Contains(x.Output, cmdTimes.Use) {
		t.Errorf("--help shouldn't display subsubcommand's usage, Got: \n %s", x.Output)
	}

	checkResultContains(t, x, "Available Commands:")
	checkResultContains(t, x, "for more information about a command")

	if strings.Contains(x.Output, "unknown flag: --help") {
		t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output)
	}

}

func TestFlagAccess(t *testing.T) {
	initialize()

	local := cmdTimes.LocalFlags()
	inherited := cmdTimes.InheritedFlags()

	for _, f := range []string{"inttwo", "strtwo", "booltwo"} {
		if local.Lookup(f) == nil {
			t.Errorf("LocalFlags expected to contain %s, Got: nil", f)
		}
	}
	if inherited.Lookup("strone") == nil {
		t.Errorf("InheritedFlags expected to contain strone, Got: nil")
	}
	if inherited.Lookup("strtwo") != nil {
		t.Errorf("InheritedFlags shouldn not contain overwritten flag strtwo")
	}
}

func TestNoNRunnableRootCommandNilInput(t *testing.T) {
	c := initialize()

	buf := new(bytes.Buffer)
	// Testing flag with invalid input
	c.SetOutput(buf)
	cmdEcho.AddCommand(cmdTimes)
	c.AddCommand(cmdPrint, cmdEcho)
	c.SetArgs([]string{})

	c.Execute()

	if !strings.Contains(buf.String(), cmdRootNoRun.Long) {
		t.Errorf("Expected to get help output, Got: \n %s", buf)
	}
}

func TestRootNoCommandHelp(t *testing.T) {
	x := rootOnlySetupTest("--help")

	checkResultOmits(t, x, "Available Commands:")
	checkResultOmits(t, x, "for more information about a command")

	if strings.Contains(x.Output, "unknown flag: --help") {
		t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output)
	}

	x = rootOnlySetupTest("echo", "--help")

	checkResultOmits(t, x, "Available Commands:")
	checkResultOmits(t, x, "for more information about a command")

	if strings.Contains(x.Output, "unknown flag: --help") {
		t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output)
	}
}

func TestRootUnknownCommand(t *testing.T) {
	r := noRRSetupTest("bogus")
	s := "Error: unknown command \"bogus\" for \"cobra-test\"\nRun 'cobra-test --help' for usage.\n"

	if r.Output != s {
		t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", s, r.Output)
	}

	r = noRRSetupTest("--strtwo=a", "bogus")
	if r.Output != s {
		t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", s, r.Output)
	}
}

func TestRootUnknownCommandSilenced(t *testing.T) {
	r := noRRSetupTestSilenced("bogus")

	if r.Output != "" {
		t.Errorf("Unexpected response.\nExpecting to be: \n\"\"\n Got:\n %q\n", r.Output)
	}

	r = noRRSetupTestSilenced("--strtwo=a", "bogus")
	if r.Output != "" {
		t.Errorf("Unexpected response.\nExpecting to be:\n\"\"\nGot:\n %q\n", r.Output)
	}
}

func TestRootSuggestions(t *testing.T) {
	outputWithSuggestions := "Error: unknown command \"%s\" for \"cobra-test\"\n\nDid you mean this?\n\t%s\n\nRun 'cobra-test --help' for usage.\n"
	outputWithoutSuggestions := "Error: unknown command \"%s\" for \"cobra-test\"\nRun 'cobra-test --help' for usage.\n"

	cmd := initializeWithRootCmd()
	cmd.AddCommand(cmdTimes)

	tests := map[string]string{
		"time":     "times",
		"tiems":    "times",
		"tims":     "times",
		"timeS":    "times",
		"rimes":    "times",
		"ti":       "times",
		"t":        "times",
		"timely":   "times",
		"ri":       "",
		"timezone": "",
		"foo":      "",
		"counts":   "times",
	}

	for typo, suggestion := range tests {
		for _, suggestionsDisabled := range []bool{false, true} {
			cmd.DisableSuggestions = suggestionsDisabled
			result := simpleTester(cmd, typo)
			expected := ""
			if len(suggestion) == 0 || suggestionsDisabled {
				expected = fmt.Sprintf(outputWithoutSuggestions, typo)
			} else {
				expected = fmt.Sprintf(outputWithSuggestions, typo, suggestion)
			}
			if result.Output != expected {
				t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", expected, result.Output)
			}
		}
	}
}

func TestFlagsBeforeCommand(t *testing.T) {
	// short without space
	x := fullSetupTest("-i10", "echo")
	if x.Error != nil {
		t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)
	}

	x = noRRSetupTest("echo", "-i=10")
	if x.Error != nil {
		t.Errorf("Valid Input shouldn't have errors, got:\n %s", x.Error)
	}

	// long with equals
	x = noRRSetupTest("--intone=123", "echo", "one", "two")
	if x.Error != nil {
		t.Errorf("Valid Input shouldn't have errors, got:\n %s", x.Error)
	}

	// With parsing error properly reported
	x = fullSetupTest("-i10E", "echo")
	if !strings.Contains(x.Error.Error(), "invalid syntax") {
		t.Errorf("Wrong error message displayed, \n %s", x.Error)
	}
}

func TestRemoveCommand(t *testing.T) {
	versionUsed = 0
	c := initializeWithRootCmd()
	c.AddCommand(cmdVersion1)
	c.RemoveCommand(cmdVersion1)
	x := fullTester(c, "version")
	if x.Error == nil {
		t.Errorf("Removed command should not have been called\n")
		return
	}
}

func TestCommandWithoutSubcommands(t *testing.T) {
	c := initializeWithRootCmd()

	x := simpleTester(c, "")
	if x.Error != nil {
		t.Errorf("Calling command without subcommands should not have error: %v", x.Error)
		return
	}
}

func TestCommandWithoutSubcommandsWithArg(t *testing.T) {
	c := initializeWithRootCmd()
	expectedArgs := []string{"arg"}

	x := simpleTester(c, "arg")
	if x.Error != nil {
		t.Errorf("Calling command without subcommands but with arg should not have error: %v", x.Error)
		return
	}
	if !reflect.DeepEqual(expectedArgs, tr) {
		t.Errorf("Calling command without subcommands but with arg has wrong args: expected: %v, actual: %v", expectedArgs, tr)
		return
	}
}

func TestReplaceCommandWithRemove(t *testing.T) {
	versionUsed = 0
	c := initializeWithRootCmd()
	c.AddCommand(cmdVersion1)
	c.RemoveCommand(cmdVersion1)
	c.AddCommand(cmdVersion2)
	x := fullTester(c, "version")
	if x.Error != nil {
		t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)
		return
	}
	if versionUsed == 1 {
		t.Errorf("Removed command shouldn't be called\n")
	}
	if versionUsed != 2 {
		t.Errorf("Replacing command should have been called but didn't\n")
	}
}

func TestDeprecatedSub(t *testing.T) {
	c := fullSetupTest("deprecated")

	checkResultContains(t, c, cmdDeprecated.Deprecated)
}

func TestPreRun(t *testing.T) {
	noRRSetupTest("echo", "one", "two")
	if echoPre == nil || echoPersPre == nil {
		t.Error("PreRun or PersistentPreRun not called")
	}
	if rootPersPre != nil || timesPersPre != nil {
		t.Error("Wrong *Pre functions called!")
	}

	noRRSetupTest("echo", "times", "one", "two")
	if timesPersPre == nil {
		t.Error("PreRun or PersistentPreRun not called")
	}
	if echoPre != nil || echoPersPre != nil || rootPersPre != nil {
		t.Error("Wrong *Pre functions called!")
	}

	noRRSetupTest("print", "one", "two")
	if rootPersPre == nil {
		t.Error("Parent PersistentPreRun not called but should not have been")
	}
	if echoPre != nil || echoPersPre != nil || timesPersPre != nil {
		t.Error("Wrong *Pre functions called!")
	}
}

// Check if cmdEchoSub gets PersistentPreRun from rootCmd even if is added last
func TestPeristentPreRunPropagation(t *testing.T) {
	rootCmd := initialize()

	// First add the cmdEchoSub to cmdPrint
	cmdPrint.AddCommand(cmdEchoSub)
	// Now add cmdPrint to rootCmd
	rootCmd.AddCommand(cmdPrint)

	rootCmd.SetArgs([]string{"print", "echosub", "lala"})
	rootCmd.Execute()

	if len(rootPersPre) == 0 || rootPersPre[0] != "lala" {
		t.Error("RootCmd PersistentPreRun not called but should have been")
	}
}

func TestGlobalNormFuncPropagation(t *testing.T) {
	normFunc := func(f *pflag.FlagSet, name string) pflag.NormalizedName {
		return pflag.NormalizedName(name)
	}

	rootCmd := initialize()
	rootCmd.SetGlobalNormalizationFunc(normFunc)
	if reflect.ValueOf(normFunc).Pointer() != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()).Pointer() {
		t.Error("rootCmd seems to have a wrong normalization function")
	}

	// First add the cmdEchoSub to cmdPrint
	cmdPrint.AddCommand(cmdEchoSub)
	if cmdPrint.GlobalNormalizationFunc() != nil && cmdEchoSub.GlobalNormalizationFunc() != nil {
		t.Error("cmdPrint and cmdEchoSub should had no normalization functions")
	}

	// Now add cmdPrint to rootCmd
	rootCmd.AddCommand(cmdPrint)
	if reflect.ValueOf(cmdPrint.GlobalNormalizationFunc()).Pointer() != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()).Pointer() ||
		reflect.ValueOf(cmdEchoSub.GlobalNormalizationFunc()).Pointer() != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()).Pointer() {
		t.Error("cmdPrint and cmdEchoSub should had the normalization function of rootCmd")
	}
}

func TestFlagOnPflagCommandLine(t *testing.T) {
	flagName := "flagOnCommandLine"
	pflag.String(flagName, "", "about my flag")
	r := fullSetupTest("--help")

	checkResultContains(t, r, flagName)

	// Reset pflag.CommandLine flagset.
	pflag.CommandLine = pflag.NewFlagSet(os.Args[0], pflag.ExitOnError)
}

func TestAddTemplateFunctions(t *testing.T) {
	AddTemplateFunc("t", func() bool { return true })
	AddTemplateFuncs(template.FuncMap{
		"f": func() bool { return false },
		"h": func() string { return "Hello," },
		"w": func() string { return "world." }})

	const usage = "Hello, world."

	c := &Command{}
	c.SetUsageTemplate(`{{if t}}{{h}}{{end}}{{if f}}{{h}}{{end}} {{w}}`)

	if us := c.UsageString(); us != usage {
		t.Errorf("c.UsageString() != \"%s\", is \"%s\"", usage, us)
	}
}

func TestUsageIsNotPrintedTwice(t *testing.T) {
	var cmd = &Command{Use: "root"}
	var sub = &Command{Use: "sub"}
	cmd.AddCommand(sub)

	r := simpleTester(cmd, "")
	if strings.Count(r.Output, "Usage:") != 1 {
		t.Error("Usage output is not printed exactly once")
	}
}

func BenchmarkInheritedFlags(b *testing.B) {
	initialize()
	cmdEcho.AddCommand(cmdTimes)
	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		cmdTimes.InheritedFlags()
	}
}

func BenchmarkLocalFlags(b *testing.B) {
	initialize()
	cmdEcho.AddCommand(cmdTimes)
	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		cmdTimes.LocalFlags()
	}
}