-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
command_test.go
4567 lines (4104 loc) · 111 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
package cli
import (
"bytes"
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"net/mail"
"os"
"sort"
"strconv"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var (
lastExitCode = 0
fakeOsExiter = func(rc int) {
lastExitCode = rc
}
fakeErrWriter = &bytes.Buffer{}
)
func init() {
OsExiter = fakeOsExiter
ErrWriter = fakeErrWriter
}
type opCounts struct {
Total, ShellComplete, OnUsageError, Before, CommandNotFound, Action, After, SubCommand int
}
func buildExtendedTestCommand() *Command {
cmd := buildMinimalTestCommand()
cmd.Name = "greet"
cmd.Flags = []Flag{
&StringFlag{
Name: "socket",
Aliases: []string{"s"},
Usage: "some 'usage' text",
Value: "value",
TakesFile: true,
},
&StringFlag{Name: "flag", Aliases: []string{"fl", "f"}},
&BoolFlag{
Name: "another-flag",
Aliases: []string{"b"},
Usage: "another usage text",
Sources: EnvVars("EXAMPLE_VARIABLE_NAME"),
},
&BoolFlag{
Name: "hidden-flag",
Hidden: true,
},
}
cmd.Commands = []*Command{{
Aliases: []string{"c"},
Flags: []Flag{
&StringFlag{
Name: "flag",
Aliases: []string{"fl", "f"},
TakesFile: true,
},
&BoolFlag{
Name: "another-flag",
Aliases: []string{"b"},
Usage: "another usage text",
},
},
Name: "config",
Usage: "another usage test",
Commands: []*Command{{
Aliases: []string{"s", "ss"},
Flags: []Flag{
&StringFlag{Name: "sub-flag", Aliases: []string{"sub-fl", "s"}},
&BoolFlag{
Name: "sub-command-flag",
Aliases: []string{"s"},
Usage: "some usage text",
},
},
Name: "sub-config",
Usage: "another usage test",
}},
}, {
Aliases: []string{"i", "in"},
Name: "info",
Usage: "retrieve generic information",
}, {
Name: "some-command",
}, {
Name: "hidden-command",
Hidden: true,
}, {
Aliases: []string{"u"},
Flags: []Flag{
&StringFlag{
Name: "flag",
Aliases: []string{"fl", "f"},
TakesFile: true,
},
&BoolFlag{
Name: "another-flag",
Aliases: []string{"b"},
Usage: "another usage text",
},
},
Name: "usage",
Usage: "standard usage text",
UsageText: `
Usage for the usage text
- formatted: Based on the specified ConfigMap and summon secrets.yml
- list: Inspect the environment for a specific process running on a Pod
- for_effect: Compare 'namespace' environment with 'local'
` + "```" + `
func() { ... }
` + "```" + `
Should be a part of the same code block
`,
Commands: []*Command{{
Aliases: []string{"su"},
Flags: []Flag{
&BoolFlag{
Name: "sub-command-flag",
Aliases: []string{"s"},
Usage: "some usage text",
},
},
Name: "sub-usage",
Usage: "standard usage text",
UsageText: "Single line of UsageText",
}},
}}
cmd.UsageText = "app [first_arg] [second_arg]"
cmd.Description = `Description of the application.`
cmd.Usage = "Some app"
cmd.Authors = []any{
"Harrison <[email protected]>",
&mail.Address{Name: "Oliver Allen", Address: "[email protected]"},
}
return cmd
}
func TestCommandFlagParsing(t *testing.T) {
cases := []struct {
testArgs []string
skipFlagParsing bool
useShortOptionHandling bool
expectedErr string
}{
// Test normal "not ignoring flags" flow
{testArgs: []string{"test-cmd", "-break", "blah", "blah"}, skipFlagParsing: false, useShortOptionHandling: false, expectedErr: "flag provided but not defined: -break"},
{testArgs: []string{"test-cmd", "blah", "blah"}, skipFlagParsing: true, useShortOptionHandling: false}, // Test SkipFlagParsing without any args that look like flags
{testArgs: []string{"test-cmd", "blah", "-break"}, skipFlagParsing: true, useShortOptionHandling: false}, // Test SkipFlagParsing with random flag arg
{testArgs: []string{"test-cmd", "blah", "-help"}, skipFlagParsing: true, useShortOptionHandling: false}, // Test SkipFlagParsing with "special" help flag arg
{testArgs: []string{"test-cmd", "blah", "-h"}, skipFlagParsing: false, useShortOptionHandling: true, expectedErr: "No help topic for 'blah'"}, // Test UseShortOptionHandling
}
for _, c := range cases {
t.Run(strings.Join(c.testArgs, " "), func(t *testing.T) {
cmd := &Command{
Writer: io.Discard,
Name: "test-cmd",
Aliases: []string{"tc"},
Usage: "this is for testing",
Description: "testing",
Action: func(context.Context, *Command) error { return nil },
SkipFlagParsing: c.skipFlagParsing,
}
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
t.Cleanup(cancel)
r := require.New(t)
err := cmd.Run(ctx, c.testArgs)
if c.expectedErr != "" {
r.EqualError(err, c.expectedErr)
} else {
r.NoError(err)
}
})
}
}
func TestParseAndRunShortOpts(t *testing.T) {
testCases := []struct {
testArgs *stringSliceArgs
expectedErr string
expectedArgs Args
}{
{testArgs: &stringSliceArgs{v: []string{"test", "-a"}}},
{testArgs: &stringSliceArgs{v: []string{"test", "-c", "arg1", "arg2"}}, expectedArgs: &stringSliceArgs{v: []string{"arg1", "arg2"}}},
{testArgs: &stringSliceArgs{v: []string{"test", "-f"}}, expectedArgs: &stringSliceArgs{v: []string{}}},
{testArgs: &stringSliceArgs{v: []string{"test", "-ac", "--fgh"}}, expectedArgs: &stringSliceArgs{v: []string{}}},
{testArgs: &stringSliceArgs{v: []string{"test", "-af"}}, expectedArgs: &stringSliceArgs{v: []string{}}},
{testArgs: &stringSliceArgs{v: []string{"test", "-cf"}}, expectedArgs: &stringSliceArgs{v: []string{}}},
{testArgs: &stringSliceArgs{v: []string{"test", "-acf"}}, expectedArgs: &stringSliceArgs{v: []string{}}},
{testArgs: &stringSliceArgs{v: []string{"test", "--acf"}}, expectedErr: "flag provided but not defined: -acf"},
{testArgs: &stringSliceArgs{v: []string{"test", "-invalid"}}, expectedErr: "flag provided but not defined: -invalid"},
{testArgs: &stringSliceArgs{v: []string{"test", "-acf", "-invalid"}}, expectedErr: "flag provided but not defined: -invalid"},
{testArgs: &stringSliceArgs{v: []string{"test", "--invalid"}}, expectedErr: "flag provided but not defined: -invalid"},
{testArgs: &stringSliceArgs{v: []string{"test", "-acf", "--invalid"}}, expectedErr: "flag provided but not defined: -invalid"},
{testArgs: &stringSliceArgs{v: []string{"test", "-acf", "arg1", "-invalid"}}, expectedErr: "flag provided but not defined: -invalid"},
{testArgs: &stringSliceArgs{v: []string{"test", "-acf", "arg1", "--invalid"}}, expectedErr: "flag provided but not defined: -invalid"},
{testArgs: &stringSliceArgs{v: []string{"test", "-acfi", "not-arg", "arg1", "-invalid"}}, expectedErr: "flag provided but not defined: -invalid"},
{testArgs: &stringSliceArgs{v: []string{"test", "-i", "ivalue"}}, expectedArgs: &stringSliceArgs{v: []string{}}},
{testArgs: &stringSliceArgs{v: []string{"test", "-i", "ivalue", "arg1"}}, expectedArgs: &stringSliceArgs{v: []string{"arg1"}}},
{testArgs: &stringSliceArgs{v: []string{"test", "-i"}}, expectedErr: "flag needs an argument: -i"},
}
for _, tc := range testCases {
t.Run(strings.Join(tc.testArgs.v, " "), func(t *testing.T) {
state := map[string]Args{"args": nil}
cmd := &Command{
Name: "test",
Usage: "this is for testing",
Description: "testing",
Action: func(_ context.Context, cmd *Command) error {
state["args"] = cmd.Args()
return nil
},
UseShortOptionHandling: true,
Writer: io.Discard,
Flags: []Flag{
&BoolFlag{Name: "abc", Aliases: []string{"a"}},
&BoolFlag{Name: "cde", Aliases: []string{"c"}},
&BoolFlag{Name: "fgh", Aliases: []string{"f"}},
&StringFlag{Name: "ijk", Aliases: []string{"i"}},
},
}
err := cmd.Run(buildTestContext(t), tc.testArgs.Slice())
r := require.New(t)
if tc.expectedErr == "" {
r.NoError(err)
} else {
r.ErrorContains(err, tc.expectedErr)
}
if tc.expectedArgs == nil {
if state["args"] != nil {
r.Len(state["args"].Slice(), 0)
} else {
r.Nil(state["args"])
}
} else {
r.Equal(tc.expectedArgs, state["args"])
}
})
}
}
func TestCommand_Run_DoesNotOverwriteErrorFromBefore(t *testing.T) {
cmd := &Command{
Name: "bar",
Before: func(context.Context, *Command) (context.Context, error) {
return nil, fmt.Errorf("before error")
},
After: func(context.Context, *Command) error {
return fmt.Errorf("after error")
},
Writer: io.Discard,
}
err := cmd.Run(buildTestContext(t), []string{"bar"})
require.ErrorContains(t, err, "before error")
require.ErrorContains(t, err, "after error")
}
func TestCommand_Run_BeforeSavesMetadata(t *testing.T) {
var receivedMsgFromAction string
var receivedMsgFromAfter string
cmd := &Command{
Name: "bar",
Before: func(ctx context.Context, cmd *Command) (context.Context, error) {
cmd.Metadata["msg"] = "hello world"
return nil, nil
},
Action: func(ctx context.Context, cmd *Command) error {
msg, ok := cmd.Metadata["msg"]
if !ok {
return errors.New("msg not found")
}
receivedMsgFromAction = msg.(string)
return nil
},
After: func(_ context.Context, cmd *Command) error {
msg, ok := cmd.Metadata["msg"]
if !ok {
return errors.New("msg not found")
}
receivedMsgFromAfter = msg.(string)
return nil
},
}
require.NoError(t, cmd.Run(buildTestContext(t), []string{"foo", "bar"}))
require.Equal(t, "hello world", receivedMsgFromAction)
require.Equal(t, "hello world", receivedMsgFromAfter)
}
func TestCommand_Run_BeforeReturnNewContext(t *testing.T) {
var receivedValFromAction, receivedValFromAfter string
type key string
bkey := key("bkey")
cmd := &Command{
Name: "bar",
Before: func(ctx context.Context, cmd *Command) (context.Context, error) {
return context.WithValue(ctx, bkey, "bval"), nil
},
Action: func(ctx context.Context, cmd *Command) error {
if val := ctx.Value(bkey); val == nil {
return errors.New("bkey value not found")
} else {
receivedValFromAction = val.(string)
}
return nil
},
After: func(ctx context.Context, cmd *Command) error {
if val := ctx.Value(bkey); val == nil {
return errors.New("bkey value not found")
} else {
receivedValFromAfter = val.(string)
}
return nil
},
}
require.NoError(t, cmd.Run(buildTestContext(t), []string{"foo", "bar"}))
require.Equal(t, "bval", receivedValFromAfter)
require.Equal(t, "bval", receivedValFromAction)
}
func TestCommand_OnUsageError_hasCommandContext(t *testing.T) {
cmd := &Command{
Name: "bar",
Flags: []Flag{
&IntFlag{Name: "flag"},
},
OnUsageError: func(_ context.Context, cmd *Command, err error, _ bool) error {
return fmt.Errorf("intercepted in %s: %s", cmd.Name, err.Error())
},
}
err := cmd.Run(buildTestContext(t), []string{"bar", "--flag=wrong"})
assert.ErrorContains(t, err, "intercepted in bar")
}
func TestCommand_OnUsageError_WithWrongFlagValue(t *testing.T) {
cmd := &Command{
Name: "bar",
Flags: []Flag{
&IntFlag{Name: "flag"},
},
OnUsageError: func(_ context.Context, _ *Command, err error, _ bool) error {
assert.ErrorContains(t, err, "invalid value \"wrong\"")
return errors.New("intercepted: " + err.Error())
},
}
err := cmd.Run(buildTestContext(t), []string{"bar", "--flag=wrong"})
assert.ErrorContains(t, err, "intercepted: invalid value")
}
func TestCommand_OnUsageError_WithSubcommand(t *testing.T) {
cmd := &Command{
Name: "bar",
Commands: []*Command{
{
Name: "baz",
},
},
Flags: []Flag{
&IntFlag{Name: "flag"},
},
OnUsageError: func(_ context.Context, _ *Command, err error, _ bool) error {
assert.ErrorContains(t, err, "invalid value \"wrong\"")
return errors.New("intercepted: " + err.Error())
},
}
require.ErrorContains(t, cmd.Run(buildTestContext(t), []string{"bar", "--flag=wrong"}), "intercepted: invalid value")
}
func TestCommand_Run_SubcommandsCanUseErrWriter(t *testing.T) {
cmd := &Command{
ErrWriter: io.Discard,
Name: "bar",
Usage: "this is for testing",
Commands: []*Command{
{
Name: "baz",
Usage: "this is for testing",
Action: func(_ context.Context, cmd *Command) error {
require.Equal(t, io.Discard, cmd.Root().ErrWriter)
return nil
},
},
},
}
require.NoError(t, cmd.Run(buildTestContext(t), []string{"bar", "baz"}))
}
func TestCommandSkipFlagParsing(t *testing.T) {
cases := []struct {
testArgs *stringSliceArgs
expectedArgs *stringSliceArgs
expectedErr error
}{
{testArgs: &stringSliceArgs{v: []string{"some-command", "some-arg", "--flag", "foo"}}, expectedArgs: &stringSliceArgs{v: []string{"some-arg", "--flag", "foo"}}, expectedErr: nil},
{testArgs: &stringSliceArgs{v: []string{"some-command", "some-arg", "--flag=foo"}}, expectedArgs: &stringSliceArgs{v: []string{"some-arg", "--flag=foo"}}, expectedErr: nil},
}
for _, c := range cases {
t.Run(strings.Join(c.testArgs.Slice(), " "), func(t *testing.T) {
var args Args
cmd := &Command{
SkipFlagParsing: true,
Name: "some-command",
Flags: []Flag{
&StringFlag{Name: "flag"},
},
Action: func(_ context.Context, cmd *Command) error {
args = cmd.Args()
return nil
},
Writer: io.Discard,
}
err := cmd.Run(buildTestContext(t), c.testArgs.Slice())
assert.Equal(t, c.expectedErr, err)
assert.Equal(t, c.expectedArgs, args)
})
}
}
func TestCommand_Run_CustomShellCompleteAcceptsMalformedFlags(t *testing.T) {
cases := []struct {
testArgs *stringSliceArgs
expectedOut string
}{
{testArgs: &stringSliceArgs{v: []string{"--undefined"}}, expectedOut: "found 0 args"},
{testArgs: &stringSliceArgs{v: []string{"--number"}}, expectedOut: "found 0 args"},
{testArgs: &stringSliceArgs{v: []string{"--number", "forty-two"}}, expectedOut: "found 0 args"},
{testArgs: &stringSliceArgs{v: []string{"--number", "42"}}, expectedOut: "found 0 args"},
{testArgs: &stringSliceArgs{v: []string{"--number", "42", "newArg"}}, expectedOut: "found 1 args"},
}
for _, c := range cases {
t.Run(strings.Join(c.testArgs.Slice(), " "), func(t *testing.T) {
out := &bytes.Buffer{}
cmd := &Command{
Writer: out,
EnableShellCompletion: true,
Name: "bar",
Usage: "this is for testing",
Flags: []Flag{
&IntFlag{
Name: "number",
Usage: "A number to parse",
},
},
ShellComplete: func(_ context.Context, cmd *Command) {
fmt.Fprintf(cmd.Root().Writer, "found %[1]d args", cmd.NArg())
},
}
osArgs := &stringSliceArgs{v: []string{"bar"}}
osArgs.v = append(osArgs.v, c.testArgs.Slice()...)
osArgs.v = append(osArgs.v, completionFlag)
r := require.New(t)
r.NoError(cmd.Run(buildTestContext(t), osArgs.Slice()))
r.Equal(c.expectedOut, out.String())
})
}
}
func TestCommand_CanAddVFlagOnSubCommands(t *testing.T) {
cmd := &Command{
Version: "some version",
Writer: io.Discard,
Name: "foo",
Usage: "this is for testing",
Commands: []*Command{
{
Name: "bar",
Flags: []Flag{
&BoolFlag{Name: "v"},
},
},
},
}
err := cmd.Run(buildTestContext(t), []string{"foo", "bar"})
assert.NoError(t, err)
}
func TestCommand_VisibleSubcCommands(t *testing.T) {
subc1 := &Command{
Name: "subc1",
Usage: "subc1 command1",
}
subc3 := &Command{
Name: "subc3",
Usage: "subc3 command2",
}
cmd := &Command{
Name: "bar",
Usage: "this is for testing",
Commands: []*Command{
subc1,
{
Name: "subc2",
Usage: "subc2 command2",
Hidden: true,
},
subc3,
},
}
assert.Equal(t, cmd.VisibleCommands(), []*Command{subc1, subc3})
}
func TestCommand_VisibleFlagCategories(t *testing.T) {
cmd := &Command{
Name: "bar",
Usage: "this is for testing",
Flags: []Flag{
&StringFlag{
Name: "strd", // no category set
},
&StringFlag{
Name: "strd1", // no category set and also hidden
Hidden: true,
},
&IntFlag{
Name: "intd",
Aliases: []string{"altd1", "altd2"},
Category: "cat1",
},
&StringFlag{
Name: "sfd",
Category: "cat2", // category set and hidden
Hidden: true,
},
},
MutuallyExclusiveFlags: []MutuallyExclusiveFlags{{
Category: "cat2",
Flags: [][]Flag{
{
&StringFlag{
Name: "mutex",
},
},
},
}},
}
cmd.MutuallyExclusiveFlags[0].propagateCategory()
vfc := cmd.VisibleFlagCategories()
require.Len(t, vfc, 3)
assert.Equal(t, vfc[0].Name(), "", "expected category name to be empty")
assert.Equal(t, vfc[0].Flags()[0].Names(), []string{"strd"})
assert.Equal(t, vfc[1].Name(), "cat1", "expected category name cat1")
require.Len(t, vfc[1].Flags(), 1, "expected flag category to have one flag")
assert.Equal(t, vfc[1].Flags()[0].Names(), []string{"intd", "altd1", "altd2"})
assert.Equal(t, vfc[2].Name(), "cat2", "expected category name cat2")
require.Len(t, vfc[2].Flags(), 1, "expected flag category to have one flag")
assert.Equal(t, vfc[2].Flags()[0].Names(), []string{"mutex"})
}
func TestCommand_RunSubcommandWithDefault(t *testing.T) {
cmd := &Command{
Version: "some version",
Name: "app",
DefaultCommand: "foo",
Commands: []*Command{
{
Name: "foo",
Action: func(context.Context, *Command) error {
return errors.New("should not run this subcommand")
},
},
{
Name: "bar",
Usage: "this is for testing",
Commands: []*Command{{}}, // some subcommand
Action: func(context.Context, *Command) error {
return nil
},
},
},
}
err := cmd.Run(buildTestContext(t), []string{"app", "bar"})
assert.NoError(t, err)
err = cmd.Run(buildTestContext(t), []string{"app"})
assert.EqualError(t, err, "should not run this subcommand")
}
func TestCommand_Run(t *testing.T) {
s := ""
cmd := &Command{
Action: func(_ context.Context, cmd *Command) error {
s = s + cmd.Args().First()
return nil
},
}
err := cmd.Run(buildTestContext(t), []string{"command", "foo"})
assert.NoError(t, err)
err = cmd.Run(buildTestContext(t), []string{"command", "bar"})
assert.NoError(t, err)
assert.Equal(t, s, "foobar")
}
var commandTests = []struct {
name string
expected bool
}{
{"foobar", true},
{"batbaz", true},
{"b", true},
{"f", true},
{"bat", false},
{"nothing", false},
}
func TestCommand_Command(t *testing.T) {
cmd := &Command{
Commands: []*Command{
{Name: "foobar", Aliases: []string{"f"}},
{Name: "batbaz", Aliases: []string{"b"}},
},
}
for _, test := range commandTests {
if test.expected {
assert.NotEmpty(t, cmd.Command(test.name))
} else {
assert.Empty(t, cmd.Command(test.name))
}
}
}
var defaultCommandTests = []struct {
cmdName string
defaultCmd string
errNotExpected bool
}{
{"foobar", "foobar", true},
{"batbaz", "foobar", true},
{"b", "", true},
{"f", "", true},
{"", "foobar", true},
{"", "", true},
{" ", "", false},
{"bat", "batbaz", true},
{"nothing", "batbaz", true},
{"nothing", "", false},
}
func TestCommand_RunDefaultCommand(t *testing.T) {
for _, test := range defaultCommandTests {
testTitle := fmt.Sprintf("command=%[1]s-default=%[2]s", test.cmdName, test.defaultCmd)
t.Run(testTitle, func(t *testing.T) {
cmd := &Command{
DefaultCommand: test.defaultCmd,
Commands: []*Command{
{Name: "foobar", Aliases: []string{"f"}},
{Name: "batbaz", Aliases: []string{"b"}},
},
}
err := cmd.Run(buildTestContext(t), []string{"c", test.cmdName})
if test.errNotExpected {
assert.NoError(t, err)
} else {
assert.Error(t, err)
}
})
}
}
var defaultCommandSubCommandTests = []struct {
cmdName string
subCmd string
defaultCmd string
errNotExpected bool
}{
{"foobar", "", "foobar", true},
{"foobar", "carly", "foobar", true},
{"batbaz", "", "foobar", true},
{"b", "", "", true},
{"f", "", "", true},
{"", "", "foobar", true},
{"", "", "", true},
{"", "jimbob", "foobar", true},
{"", "j", "foobar", true},
{"", "carly", "foobar", true},
{"", "jimmers", "foobar", false},
{"", "jimmers", "", true},
{" ", "jimmers", "foobar", false},
{"", "", "", true},
{" ", "", "", false},
{" ", "j", "", false},
{"bat", "", "batbaz", true},
{"nothing", "", "batbaz", true},
{"nothing", "", "", false},
{"nothing", "j", "batbaz", false},
{"nothing", "carly", "", false},
}
func TestCommand_RunDefaultCommandWithSubCommand(t *testing.T) {
for _, test := range defaultCommandSubCommandTests {
testTitle := fmt.Sprintf("command=%[1]s-subcmd=%[2]s-default=%[3]s", test.cmdName, test.subCmd, test.defaultCmd)
t.Run(testTitle, func(t *testing.T) {
cmd := &Command{
DefaultCommand: test.defaultCmd,
Commands: []*Command{
{
Name: "foobar",
Aliases: []string{"f"},
Commands: []*Command{
{Name: "jimbob", Aliases: []string{"j"}},
{Name: "carly"},
},
},
{Name: "batbaz", Aliases: []string{"b"}},
},
}
err := cmd.Run(buildTestContext(t), []string{"c", test.cmdName, test.subCmd})
if test.errNotExpected {
assert.NoError(t, err)
} else {
assert.Error(t, err)
}
})
}
}
var defaultCommandFlagTests = []struct {
cmdName string
flag string
defaultCmd string
errNotExpected bool
}{
{"foobar", "", "foobar", true},
{"foobar", "-c derp", "foobar", true},
{"batbaz", "", "foobar", true},
{"b", "", "", true},
{"f", "", "", true},
{"", "", "foobar", true},
{"", "", "", true},
{"", "-j", "foobar", true},
{"", "-j", "foobar", true},
{"", "-c derp", "foobar", true},
{"", "--carly=derp", "foobar", true},
{"", "-j", "foobar", true},
{"", "-j", "", true},
{" ", "-j", "foobar", true},
{"", "", "", true},
{" ", "", "", false},
{" ", "-j", "", false},
{"bat", "", "batbaz", true},
{"nothing", "", "batbaz", true},
{"nothing", "", "", false},
{"nothing", "--jimbob", "batbaz", true},
{"nothing", "--carly", "", false},
}
func TestCommand_RunDefaultCommandWithFlags(t *testing.T) {
for _, test := range defaultCommandFlagTests {
testTitle := fmt.Sprintf("command=%[1]s-flag=%[2]s-default=%[3]s", test.cmdName, test.flag, test.defaultCmd)
t.Run(testTitle, func(t *testing.T) {
cmd := &Command{
DefaultCommand: test.defaultCmd,
Flags: []Flag{
&StringFlag{
Name: "carly",
Aliases: []string{"c"},
Required: false,
},
&BoolFlag{
Name: "jimbob",
Aliases: []string{"j"},
Required: false,
Value: true,
},
},
Commands: []*Command{
{
Name: "foobar",
Aliases: []string{"f"},
},
{Name: "batbaz", Aliases: []string{"b"}},
},
}
appArgs := []string{"c"}
if test.flag != "" {
flags := strings.Split(test.flag, " ")
if len(flags) > 1 {
appArgs = append(appArgs, flags...)
}
flags = strings.Split(test.flag, "=")
if len(flags) > 1 {
appArgs = append(appArgs, flags...)
}
}
appArgs = append(appArgs, test.cmdName)
err := cmd.Run(buildTestContext(t), appArgs)
if test.errNotExpected {
assert.NoError(t, err)
} else {
assert.Error(t, err)
}
})
}
}
func TestCommand_FlagsFromExtPackage(t *testing.T) {
var someint int
flag.IntVar(&someint, "epflag", 2, "ext package flag usage")
// Based on source code we can reset the global flag parsing this way
defer func() {
flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
}()
cmd := &Command{
AllowExtFlags: true,
Flags: []Flag{
&StringFlag{
Name: "carly",
Aliases: []string{"c"},
Required: false,
},
&BoolFlag{
Name: "jimbob",
Aliases: []string{"j"},
Required: false,
Value: true,
},
},
}
err := cmd.Run(buildTestContext(t), []string{"foo", "-c", "cly", "--epflag", "10"})
assert.NoError(t, err)
assert.Equal(t, someint, int(10))
cmd = &Command{
Flags: []Flag{
&StringFlag{
Name: "carly",
Aliases: []string{"c"},
Required: false,
},
&BoolFlag{
Name: "jimbob",
Aliases: []string{"j"},
Required: false,
Value: true,
},
},
}
// this should return an error since epflag shouldnt be registered
err = cmd.Run(buildTestContext(t), []string{"foo", "-c", "cly", "--epflag", "10"})
assert.Error(t, err)
}
func TestCommand_Setup_defaultsReader(t *testing.T) {
cmd := &Command{}
cmd.setupDefaults([]string{"cli.test"})
assert.Equal(t, cmd.Reader, os.Stdin)
}
func TestCommand_Setup_defaultsWriter(t *testing.T) {
cmd := &Command{}
cmd.setupDefaults([]string{"cli.test"})
assert.Equal(t, cmd.Writer, os.Stdout)
}
func TestCommand_CommandWithFlagBeforeTerminator(t *testing.T) {
var parsedOption string
var args Args
cmd := &Command{
Commands: []*Command{
{
Name: "cmd",
Flags: []Flag{
&StringFlag{Name: "option", Value: "", Usage: "some option"},
},
Action: func(_ context.Context, cmd *Command) error {
parsedOption = cmd.String("option")
args = cmd.Args()
return nil
},
},
},
}
require.NoError(t, cmd.Run(buildTestContext(t), []string{"", "cmd", "--option", "my-option", "my-arg", "--", "--notARealFlag"}))
require.Equal(t, "my-option", parsedOption)
require.Equal(t, "my-arg", args.Get(0))
require.Equal(t, "--", args.Get(1))
require.Equal(t, "--notARealFlag", args.Get(2))
}
func TestCommand_CommandWithDash(t *testing.T) {
var args Args
cmd := &Command{
Commands: []*Command{
{
Name: "cmd",
Action: func(_ context.Context, cmd *Command) error {
args = cmd.Args()
return nil
},
},
},
}
require.NoError(t, cmd.Run(buildTestContext(t), []string{"", "cmd", "my-arg", "-"}))
require.NotNil(t, args)
require.Equal(t, "my-arg", args.Get(0))
require.Equal(t, "-", args.Get(1))
}
func TestCommand_CommandWithNoFlagBeforeTerminator(t *testing.T) {
var args Args
cmd := &Command{
Commands: []*Command{
{
Name: "cmd",
Action: func(_ context.Context, cmd *Command) error {
args = cmd.Args()
return nil
},
},
},
}
require.NoError(t, cmd.Run(buildTestContext(t), []string{"", "cmd", "my-arg", "--", "notAFlagAtAll"}))
require.NotNil(t, args)
require.Equal(t, "my-arg", args.Get(0))
require.Equal(t, "--", args.Get(1))
require.Equal(t, "notAFlagAtAll", args.Get(2))
}
func TestCommand_SkipFlagParsing(t *testing.T) {
var args Args
cmd := &Command{
SkipFlagParsing: true,
Action: func(_ context.Context, cmd *Command) error {
args = cmd.Args()
return nil