Debian Codegraph @

command_test.go

raw symbols SCIP
1 package cli
2
3 import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "flag"
9 "fmt"
10 "io"
11 "net/mail"
12 "os"
13 "sort"
14 "strconv"
15 "strings"
16 "testing"
17 "time"
18
19 "github.com/stretchr/testify/assert"
20 "github.com/stretchr/testify/require"
21 )
22
23 var (
24 lastExitCode = 0
25 fakeOsExiter = func(rc int) {
26 lastExitCode = rc
27 }
28 fakeErrWriter = &bytes.Buffer{}
29 )
30
31 func init() {
32 OsExiter = fakeOsExiter
33 ErrWriter = fakeErrWriter
34 }
35
36 type opCounts struct {
37 Total, ShellComplete, OnUsageError, Before, CommandNotFound, Action, After, SubCommand int
38 }
39
40 func buildExtendedTestCommand() *Command {
41 cmd := buildMinimalTestCommand()
42 cmd.Name = "greet"
43 cmd.Flags = []Flag{
44 &StringFlag{
45 Name: "socket",
46 Aliases: []string{"s"},
47 Usage: "some 'usage' text",
48 Value: "value",
49 TakesFile: true,
50 },
51 &StringFlag{Name: "flag", Aliases: []string{"fl", "f"}},
52 &BoolFlag{
53 Name: "another-flag",
54 Aliases: []string{"b"},
55 Usage: "another usage text",
56 Sources: EnvVars("EXAMPLE_VARIABLE_NAME"),
57 },
58 &BoolFlag{
59 Name: "hidden-flag",
60 Hidden: true,
61 },
62 }
63 cmd.Commands = []*Command{{
64 Aliases: []string{"c"},
65 Flags: []Flag{
66 &StringFlag{
67 Name: "flag",
68 Aliases: []string{"fl", "f"},
69 TakesFile: true,
70 },
71 &BoolFlag{
72 Name: "another-flag",
73 Aliases: []string{"b"},
74 Usage: "another usage text",
75 },
76 },
77 Name: "config",
78 Usage: "another usage test",
79 Commands: []*Command{{
80 Aliases: []string{"s", "ss"},
81 Flags: []Flag{
82 &StringFlag{Name: "sub-flag", Aliases: []string{"sub-fl", "s"}},
83 &BoolFlag{
84 Name: "sub-command-flag",
85 Aliases: []string{"s"},
86 Usage: "some usage text",
87 },
88 },
89 Name: "sub-config",
90 Usage: "another usage test",
91 }},
92 }, {
93 Aliases: []string{"i", "in"},
94 Name: "info",
95 Usage: "retrieve generic information",
96 }, {
97 Name: "some-command",
98 }, {
99 Name: "hidden-command",
100 Hidden: true,
101 Flags: []Flag{
102 &BoolFlag{
103 Name: "completable",
104 },
105 },
106 }, {
107 Aliases: []string{"u"},
108 Flags: []Flag{
109 &StringFlag{
110 Name: "flag",
111 Aliases: []string{"fl", "f"},
112 TakesFile: true,
113 },
114 &BoolFlag{
115 Name: "another-flag",
116 Aliases: []string{"b"},
117 Usage: "another usage text",
118 },
119 },
120 Name: "usage",
121 Usage: "standard usage text",
122 UsageText: `
123 Usage for the usage text
124 - formatted: Based on the specified ConfigMap and summon secrets.yml
125 - list: Inspect the environment for a specific process running on a Pod
126 - for_effect: Compare 'namespace' environment with 'local'
127
128 ` + "```" + `
129 func() { ... }
130 ` + "```" + `
131
132 Should be a part of the same code block
133 `,
134 Commands: []*Command{{
135 Aliases: []string{"su"},
136 Flags: []Flag{
137 &BoolFlag{
138 Name: "sub-command-flag",
139 Aliases: []string{"s"},
140 Usage: "some usage text",
141 },
142 },
143 Name: "sub-usage",
144 Usage: "standard usage text",
145 UsageText: "Single line of UsageText",
146 }},
147 }}
148 cmd.UsageText = "app [first_arg] [second_arg]"
149 cmd.Description = `Description of the application.`
150 cmd.Usage = "Some app"
151 cmd.Authors = []any{
152 "Harrison <[email protected]>",
153 &mail.Address{Name: "Oliver Allen", Address: "[email protected]"},
154 }
155
156 return cmd
157 }
158
159 func TestCommandFlagParsing(t *testing.T) {
160 cases := []struct {
161 testArgs []string
162 skipFlagParsing bool
163 useShortOptionHandling bool
164 expectedErr string
165 }{
166 // Test normal "not ignoring flags" flow
167 {testArgs: []string{"test-cmd", "-break", "blah", "blah"}, skipFlagParsing: false, useShortOptionHandling: false, expectedErr: "flag provided but not defined: -break"},
168 {testArgs: []string{"test-cmd", "blah", "blah"}, skipFlagParsing: true, useShortOptionHandling: false}, // Test SkipFlagParsing without any args that look like flags
169 {testArgs: []string{"test-cmd", "blah", "-break"}, skipFlagParsing: true, useShortOptionHandling: false}, // Test SkipFlagParsing with random flag arg
170 {testArgs: []string{"test-cmd", "blah", "-help"}, skipFlagParsing: true, useShortOptionHandling: false}, // Test SkipFlagParsing with "special" help flag arg
171 {testArgs: []string{"test-cmd", "blah", "-h"}, skipFlagParsing: false, useShortOptionHandling: true, expectedErr: "No help topic for 'blah'"}, // Test UseShortOptionHandling
172 }
173
174 for _, c := range cases {
175 t.Run(strings.Join(c.testArgs, " "), func(t *testing.T) {
176 cmd := &Command{
177 Writer: io.Discard,
178 Name: "test-cmd",
179 Aliases: []string{"tc"},
180 Usage: "this is for testing",
181 Description: "testing",
182 Action: func(context.Context, *Command) error { return nil },
183 SkipFlagParsing: c.skipFlagParsing,
184 }
185
186 ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
187 t.Cleanup(cancel)
188
189 r := require.New(t)
190
191 err := cmd.Run(ctx, c.testArgs)
192
193 if c.expectedErr != "" {
194 r.EqualError(err, c.expectedErr)
195 } else {
196 r.NoError(err)
197 }
198 })
199 }
200 }
201
202 func TestParseAndRunShortOpts(t *testing.T) {
203 testCases := []struct {
204 testArgs *stringSliceArgs
205 expectedErr string
206 expectedArgs Args
207 }{
208 {testArgs: &stringSliceArgs{v: []string{"test", "-a"}}},
209 {testArgs: &stringSliceArgs{v: []string{"test", "-c", "arg1", "arg2"}}, expectedArgs: &stringSliceArgs{v: []string{"arg1", "arg2"}}},
210 {testArgs: &stringSliceArgs{v: []string{"test", "-f"}}, expectedArgs: &stringSliceArgs{v: []string{}}},
211 {testArgs: &stringSliceArgs{v: []string{"test", "-ac", "--fgh"}}, expectedArgs: &stringSliceArgs{v: []string{}}},
212 {testArgs: &stringSliceArgs{v: []string{"test", "-af"}}, expectedArgs: &stringSliceArgs{v: []string{}}},
213 {testArgs: &stringSliceArgs{v: []string{"test", "-cf"}}, expectedArgs: &stringSliceArgs{v: []string{}}},
214 {testArgs: &stringSliceArgs{v: []string{"test", "-acf"}}, expectedArgs: &stringSliceArgs{v: []string{}}},
215 {testArgs: &stringSliceArgs{v: []string{"test", "--acf"}}, expectedErr: "flag provided but not defined: -acf"},
216 {testArgs: &stringSliceArgs{v: []string{"test", "-invalid"}}, expectedErr: "flag provided but not defined: -invalid"},
217 {testArgs: &stringSliceArgs{v: []string{"test", "-acf", "-invalid"}}, expectedErr: "flag provided but not defined: -invalid"},
218 {testArgs: &stringSliceArgs{v: []string{"test", "--invalid"}}, expectedErr: "flag provided but not defined: -invalid"},
219 {testArgs: &stringSliceArgs{v: []string{"test", "-acf", "--invalid"}}, expectedErr: "flag provided but not defined: -invalid"},
220 {testArgs: &stringSliceArgs{v: []string{"test", "-acf", "arg1", "-invalid"}}, expectedErr: "flag provided but not defined: -invalid"},
221 {testArgs: &stringSliceArgs{v: []string{"test", "-acf", "arg1", "--invalid"}}, expectedErr: "flag provided but not defined: -invalid"},
222 {testArgs: &stringSliceArgs{v: []string{"test", "-acfi", "not-arg", "arg1", "-invalid"}}, expectedErr: "flag provided but not defined: -invalid"},
223 {testArgs: &stringSliceArgs{v: []string{"test", "-i", "ivalue"}}, expectedArgs: &stringSliceArgs{v: []string{}}},
224 {testArgs: &stringSliceArgs{v: []string{"test", "-i", "ivalue", "arg1"}}, expectedArgs: &stringSliceArgs{v: []string{"arg1"}}},
225 {testArgs: &stringSliceArgs{v: []string{"test", "-i"}}, expectedErr: "flag needs an argument: -i"},
226 }
227
228 for _, tc := range testCases {
229 t.Run(strings.Join(tc.testArgs.v, " "), func(t *testing.T) {
230 state := map[string]Args{"args": nil}
231
232 cmd := &Command{
233 Name: "test",
234 Usage: "this is for testing",
235 Description: "testing",
236 Action: func(_ context.Context, cmd *Command) error {
237 state["args"] = cmd.Args()
238 return nil
239 },
240 UseShortOptionHandling: true,
241 Writer: io.Discard,
242 Flags: []Flag{
243 &BoolFlag{Name: "abc", Aliases: []string{"a"}},
244 &BoolFlag{Name: "cde", Aliases: []string{"c"}},
245 &BoolFlag{Name: "fgh", Aliases: []string{"f"}},
246 &StringFlag{Name: "ijk", Aliases: []string{"i"}},
247 },
248 }
249
250 err := cmd.Run(buildTestContext(t), tc.testArgs.Slice())
251
252 r := require.New(t)
253
254 if tc.expectedErr == "" {
255 r.NoError(err)
256 } else {
257 r.ErrorContains(err, tc.expectedErr)
258 }
259
260 if tc.expectedArgs == nil {
261 if state["args"] != nil {
262 r.Len(state["args"].Slice(), 0)
263 } else {
264 r.Nil(state["args"])
265 }
266 } else {
267 r.Equal(tc.expectedArgs, state["args"])
268 }
269 })
270 }
271 }
272
273 func TestCommand_Run_DoesNotOverwriteErrorFromBefore(t *testing.T) {
274 cmd := &Command{
275 Name: "bar",
276 Before: func(context.Context, *Command) (context.Context, error) {
277 return nil, fmt.Errorf("before error")
278 },
279 After: func(context.Context, *Command) error {
280 return fmt.Errorf("after error")
281 },
282 Writer: io.Discard,
283 }
284
285 err := cmd.Run(buildTestContext(t), []string{"bar"})
286
287 require.ErrorContains(t, err, "before error")
288 require.ErrorContains(t, err, "after error")
289 }
290
291 func TestCommand_Run_BeforeSavesMetadata(t *testing.T) {
292 var receivedMsgFromAction string
293 var receivedMsgFromAfter string
294
295 cmd := &Command{
296 Name: "bar",
297 Before: func(ctx context.Context, cmd *Command) (context.Context, error) {
298 cmd.Metadata["msg"] = "hello world"
299 return nil, nil
300 },
301 Action: func(ctx context.Context, cmd *Command) error {
302 msg, ok := cmd.Metadata["msg"]
303 if !ok {
304 return errors.New("msg not found")
305 }
306 receivedMsgFromAction = msg.(string)
307
308 return nil
309 },
310 After: func(_ context.Context, cmd *Command) error {
311 msg, ok := cmd.Metadata["msg"]
312 if !ok {
313 return errors.New("msg not found")
314 }
315 receivedMsgFromAfter = msg.(string)
316 return nil
317 },
318 }
319
320 require.NoError(t, cmd.Run(buildTestContext(t), []string{"foo", "bar"}))
321 require.Equal(t, "hello world", receivedMsgFromAction)
322 require.Equal(t, "hello world", receivedMsgFromAfter)
323 }
324
325 func TestCommand_Run_BeforeReturnNewContext(t *testing.T) {
326 var receivedValFromAction, receivedValFromAfter string
327 type key string
328
329 bkey := key("bkey")
330
331 cmd := &Command{
332 Name: "bar",
333 Before: func(ctx context.Context, cmd *Command) (context.Context, error) {
334 return context.WithValue(ctx, bkey, "bval"), nil
335 },
336 Action: func(ctx context.Context, cmd *Command) error {
337 if val := ctx.Value(bkey); val == nil {
338 return errors.New("bkey value not found")
339 } else {
340 receivedValFromAction = val.(string)
341 }
342 return nil
343 },
344 After: func(ctx context.Context, cmd *Command) error {
345 if val := ctx.Value(bkey); val == nil {
346 return errors.New("bkey value not found")
347 } else {
348 receivedValFromAfter = val.(string)
349 }
350 return nil
351 },
352 }
353
354 require.NoError(t, cmd.Run(buildTestContext(t), []string{"foo", "bar"}))
355 require.Equal(t, "bval", receivedValFromAfter)
356 require.Equal(t, "bval", receivedValFromAction)
357 }
358
359 type ctxKey string
360
361 // ctxCollector is a small helper to collect context values.
362 type ctxCollector struct {
363 // keys are the keys to check the context for.
364 keys []ctxKey
365
366 // m maps from function name to context name to value.
367 m map[string]map[ctxKey]string
368 }
369
370 func (cc *ctxCollector) collect(ctx context.Context, fnName string) {
371 if cc.m == nil {
372 cc.m = make(map[string]map[ctxKey]string)
373 }
374
375 if _, ok := cc.m[fnName]; !ok {
376 cc.m[fnName] = make(map[ctxKey]string)
377 }
378
379 for _, k := range cc.keys {
380 if val := ctx.Value(k); val != nil {
381 cc.m[fnName][k] = val.(string)
382 }
383 }
384 }
385
386 func TestCommand_Run_BeforeReturnNewContextSubcommand(t *testing.T) {
387 bkey := ctxKey("bkey")
388 bkey2 := ctxKey("bkey2")
389
390 cc := &ctxCollector{keys: []ctxKey{bkey, bkey2}}
391 cmd := &Command{
392 Name: "bar",
393 Before: func(ctx context.Context, cmd *Command) (context.Context, error) {
394 return context.WithValue(ctx, bkey, "bval"), nil
395 },
396 After: func(ctx context.Context, cmd *Command) error {
397 cc.collect(ctx, "bar.After")
398 return nil
399 },
400 Commands: []*Command{
401 {
402 Name: "baz",
403 Before: func(ctx context.Context, cmd *Command) (context.Context, error) {
404 return context.WithValue(ctx, bkey2, "bval2"), nil
405 },
406 Action: func(ctx context.Context, cmd *Command) error {
407 cc.collect(ctx, "baz.Action")
408 return nil
409 },
410 After: func(ctx context.Context, cmd *Command) error {
411 cc.collect(ctx, "baz.After")
412 return nil
413 },
414 },
415 },
416 }
417
418 require.NoError(t, cmd.Run(buildTestContext(t), []string{"bar", "baz"}))
419 expected := map[string]map[ctxKey]string{
420 "bar.After": {
421 bkey: "bval",
422 bkey2: "bval2",
423 },
424 "baz.Action": {
425 bkey: "bval",
426 bkey2: "bval2",
427 },
428 "baz.After": {
429 bkey: "bval",
430 bkey2: "bval2",
431 },
432 }
433 require.Equal(t, expected, cc.m)
434 }
435
436 func TestCommand_Run_FlagActionContext(t *testing.T) {
437 bkey := ctxKey("bkey")
438 bkey2 := ctxKey("bkey2")
439
440 cc := &ctxCollector{keys: []ctxKey{bkey, bkey2}}
441 cmd := &Command{
442 Name: "bar",
443 Before: func(ctx context.Context, cmd *Command) (context.Context, error) {
444 return context.WithValue(ctx, bkey, "bval"), nil
445 },
446 Flags: []Flag{
447 &StringFlag{
448 Name: "foo",
449 Action: func(ctx context.Context, cmd *Command, _ string) error {
450 cc.collect(ctx, "bar.foo.Action")
451 return nil
452 },
453 },
454 },
455 Commands: []*Command{
456 {
457 Name: "baz",
458 Before: func(ctx context.Context, cmd *Command) (context.Context, error) {
459 return context.WithValue(ctx, bkey2, "bval2"), nil
460 },
461 Flags: []Flag{
462 &StringFlag{
463 Name: "goo",
464 Action: func(ctx context.Context, cmd *Command, _ string) error {
465 cc.collect(ctx, "baz.goo.Action")
466 return nil
467 },
468 },
469 },
470 Action: func(ctx context.Context, cmd *Command) error {
471 return nil
472 },
473 },
474 },
475 }
476
477 require.NoError(t, cmd.Run(buildTestContext(t), []string{"bar", "--foo", "value", "baz", "--goo", "value"}))
478 expected := map[string]map[ctxKey]string{
479 "bar.foo.Action": {
480 bkey: "bval",
481 bkey2: "bval2",
482 },
483 "baz.goo.Action": {
484 bkey: "bval",
485 bkey2: "bval2",
486 },
487 }
488 require.Equal(t, expected, cc.m)
489 }
490
491 func TestCommand_OnUsageError_hasCommandContext(t *testing.T) {
492 cmd := &Command{
493 Name: "bar",
494 Flags: []Flag{
495 &Int64Flag{Name: "flag"},
496 },
497 OnUsageError: func(_ context.Context, cmd *Command, err error, _ bool) error {
498 return fmt.Errorf("intercepted in %s: %s", cmd.Name, err.Error())
499 },
500 }
501
502 err := cmd.Run(buildTestContext(t), []string{"bar", "--flag=wrong"})
503 assert.ErrorContains(t, err, "intercepted in bar")
504 }
505
506 func TestCommand_OnUsageError_WithWrongFlagValue(t *testing.T) {
507 cmd := &Command{
508 Name: "bar",
509 Flags: []Flag{
510 &Int64Flag{Name: "flag"},
511 },
512 OnUsageError: func(_ context.Context, _ *Command, err error, _ bool) error {
513 assert.ErrorContains(t, err, "strconv.ParseInt: parsing \"wrong\"")
514 return errors.New("intercepted: " + err.Error())
515 },
516 }
517
518 err := cmd.Run(buildTestContext(t), []string{"bar", "--flag=wrong"})
519 assert.ErrorContains(t, err, "intercepted: invalid value \"wrong\" for flag -flag: strconv.ParseInt: parsing \"wrong\"")
520 }
521
522 func TestCommand_OnUsageError_WithSubcommand(t *testing.T) {
523 cmd := &Command{
524 Name: "bar",
525 Commands: []*Command{
526 {
527 Name: "baz",
528 },
529 },
530 Flags: []Flag{
531 &Int64Flag{Name: "flag"},
532 },
533 OnUsageError: func(_ context.Context, _ *Command, err error, _ bool) error {
534 assert.ErrorContains(t, err, "parsing \"wrong\": invalid syntax")
535 return errors.New("intercepted: " + err.Error())
536 },
537 }
538
539 require.ErrorContains(t, cmd.Run(buildTestContext(t), []string{"bar", "--flag=wrong"}),
540 "intercepted: invalid value \"wrong\" for flag -flag: strconv.ParseInt: parsing \"wrong\": invalid syntax")
541 }
542
543 func TestCommand_Run_SubcommandsCanUseErrWriter(t *testing.T) {
544 cmd := &Command{
545 ErrWriter: io.Discard,
546 Name: "bar",
547 Usage: "this is for testing",
548 Commands: []*Command{
549 {
550 Name: "baz",
551 Usage: "this is for testing",
552 Action: func(_ context.Context, cmd *Command) error {
553 require.Equal(t, io.Discard, cmd.Root().ErrWriter)
554
555 return nil
556 },
557 },
558 },
559 }
560
561 require.NoError(t, cmd.Run(buildTestContext(t), []string{"bar", "baz"}))
562 }
563
564 func TestCommandSkipFlagParsing(t *testing.T) {
565 cases := []struct {
566 testArgs *stringSliceArgs
567 expectedArgs *stringSliceArgs
568 expectedErr error
569 }{
570 {testArgs: &stringSliceArgs{v: []string{"some-command", "some-arg", "--flag", "foo"}}, expectedArgs: &stringSliceArgs{v: []string{"some-arg", "--flag", "foo"}}, expectedErr: nil},
571 {testArgs: &stringSliceArgs{v: []string{"some-command", "some-arg", "--flag=foo"}}, expectedArgs: &stringSliceArgs{v: []string{"some-arg", "--flag=foo"}}, expectedErr: nil},
572 }
573
574 for _, c := range cases {
575 t.Run(strings.Join(c.testArgs.Slice(), " "), func(t *testing.T) {
576 var args Args
577 cmd := &Command{
578 SkipFlagParsing: true,
579 Name: "some-command",
580 Flags: []Flag{
581 &StringFlag{Name: "flag"},
582 },
583 Action: func(_ context.Context, cmd *Command) error {
584 args = cmd.Args()
585 return nil
586 },
587 Writer: io.Discard,
588 }
589
590 err := cmd.Run(buildTestContext(t), c.testArgs.Slice())
591 assert.Equal(t, c.expectedErr, err)
592 assert.Equal(t, c.expectedArgs, args)
593 })
594 }
595 }
596
597 func TestCommand_Run_CustomShellCompleteAcceptsMalformedFlags(t *testing.T) {
598 cases := []struct {
599 testArgs *stringSliceArgs
600 expectedOut string
601 }{
602 {testArgs: &stringSliceArgs{v: []string{"--undefined"}}, expectedOut: "found 1 args"},
603 {testArgs: &stringSliceArgs{v: []string{"--number"}}, expectedOut: "found 1 args"},
604 {testArgs: &stringSliceArgs{v: []string{"--number", "forty-two"}}, expectedOut: "found 0 args"},
605 {testArgs: &stringSliceArgs{v: []string{"--number", "42"}}, expectedOut: "found 0 args"},
606 {testArgs: &stringSliceArgs{v: []string{"--number", "42", "newArg"}}, expectedOut: "found 1 args"},
607 }
608
609 for _, c := range cases {
610 t.Run(strings.Join(c.testArgs.Slice(), " "), func(t *testing.T) {
611 out := &bytes.Buffer{}
612 cmd := &Command{
613 Writer: out,
614 EnableShellCompletion: true,
615 Name: "bar",
616 Usage: "this is for testing",
617 Flags: []Flag{
618 &Int64Flag{
619 Name: "number",
620 Usage: "A number to parse",
621 },
622 },
623 ShellComplete: func(_ context.Context, cmd *Command) {
624 fmt.Fprintf(cmd.Root().Writer, "found %[1]d args", cmd.NArg())
625 },
626 }
627
628 osArgs := &stringSliceArgs{v: []string{"bar"}}
629 osArgs.v = append(osArgs.v, c.testArgs.Slice()...)
630 osArgs.v = append(osArgs.v, completionFlag)
631
632 r := require.New(t)
633
634 r.NoError(cmd.Run(buildTestContext(t), osArgs.Slice()))
635 r.Equal(c.expectedOut, out.String())
636 })
637 }
638 }
639
640 func TestCommand_CanAddVFlagOnSubCommands(t *testing.T) {
641 cmd := &Command{
642 Version: "some version",
643 Writer: io.Discard,
644 Name: "foo",
645 Usage: "this is for testing",
646 Commands: []*Command{
647 {
648 Name: "bar",
649 Flags: []Flag{
650 &BoolFlag{Name: "v"},
651 },
652 },
653 },
654 }
655
656 err := cmd.Run(buildTestContext(t), []string{"foo", "bar"})
657 assert.NoError(t, err)
658 }
659
660 func TestCommand_VisibleSubcCommands(t *testing.T) {
661 subc1 := &Command{
662 Name: "subc1",
663 Usage: "subc1 command1",
664 }
665 subc3 := &Command{
666 Name: "subc3",
667 Usage: "subc3 command2",
668 }
669 cmd := &Command{
670 Name: "bar",
671 Usage: "this is for testing",
672 Commands: []*Command{
673 subc1,
674 {
675 Name: "subc2",
676 Usage: "subc2 command2",
677 Hidden: true,
678 },
679 subc3,
680 },
681 }
682
683 assert.Equal(t, cmd.VisibleCommands(), []*Command{subc1, subc3})
684 }
685
686 func TestCommand_VisibleFlagCategories(t *testing.T) {
687 cmd := &Command{
688 Name: "bar",
689 Usage: "this is for testing",
690 Flags: []Flag{
691 &StringFlag{
692 Name: "strd", // no category set
693 },
694 &StringFlag{
695 Name: "strd1", // no category set and also hidden
696 Hidden: true,
697 },
698 &Int64Flag{
699 Name: "intd",
700 Aliases: []string{"altd1", "altd2"},
701 Category: "cat1",
702 },
703 &StringFlag{
704 Name: "sfd",
705 Category: "cat2", // category set and hidden
706 Hidden: true,
707 },
708 },
709 MutuallyExclusiveFlags: []MutuallyExclusiveFlags{{
710 Category: "cat2",
711 Flags: [][]Flag{
712 {
713 &StringFlag{
714 Name: "mutex",
715 },
716 },
717 },
718 }},
719 }
720
721 cmd.MutuallyExclusiveFlags[0].propagateCategory()
722
723 vfc := cmd.VisibleFlagCategories()
724 require.Len(t, vfc, 3)
725
726 assert.Equal(t, vfc[0].Name(), "", "expected category name to be empty")
727 assert.Equal(t, vfc[0].Flags()[0].Names(), []string{"strd"})
728
729 assert.Equal(t, vfc[1].Name(), "cat1", "expected category name cat1")
730 require.Len(t, vfc[1].Flags(), 1, "expected flag category to have one flag")
731 assert.Equal(t, vfc[1].Flags()[0].Names(), []string{"intd", "altd1", "altd2"})
732
733 assert.Equal(t, vfc[2].Name(), "cat2", "expected category name cat2")
734 require.Len(t, vfc[2].Flags(), 1, "expected flag category to have one flag")
735 assert.Equal(t, vfc[2].Flags()[0].Names(), []string{"mutex"})
736 }
737
738 func TestCommand_RunSubcommandWithDefault(t *testing.T) {
739 cmd := &Command{
740 Version: "some version",
741 Name: "app",
742 DefaultCommand: "foo",
743 Commands: []*Command{
744 {
745 Name: "foo",
746 Action: func(context.Context, *Command) error {
747 return errors.New("should not run this subcommand")
748 },
749 },
750 {
751 Name: "bar",
752 Usage: "this is for testing",
753 Commands: []*Command{{}}, // some subcommand
754 Action: func(context.Context, *Command) error {
755 return nil
756 },
757 },
758 },
759 }
760
761 err := cmd.Run(buildTestContext(t), []string{"app", "bar"})
762 assert.NoError(t, err)
763
764 err = cmd.Run(buildTestContext(t), []string{"app"})
765 assert.EqualError(t, err, "should not run this subcommand")
766 }
767
768 func TestCommand_Run(t *testing.T) {
769 s := ""
770
771 cmd := &Command{
772 Action: func(_ context.Context, cmd *Command) error {
773 s = s + cmd.Args().First()
774 return nil
775 },
776 }
777
778 err := cmd.Run(buildTestContext(t), []string{"command", "foo"})
779 assert.NoError(t, err)
780 err = cmd.Run(buildTestContext(t), []string{"command", "bar"})
781 assert.NoError(t, err)
782 assert.Equal(t, s, "foobar")
783 }
784
785 var commandTests = []struct {
786 name string
787 expected bool
788 }{
789 {"foobar", true},
790 {"batbaz", true},
791 {"b", true},
792 {"f", true},
793 {"bat", false},
794 {"nothing", false},
795 }
796
797 func TestCommand_Command(t *testing.T) {
798 cmd := &Command{
799 Commands: []*Command{
800 {Name: "foobar", Aliases: []string{"f"}},
801 {Name: "batbaz", Aliases: []string{"b"}},
802 },
803 }
804
805 for _, test := range commandTests {
806 if test.expected {
807 assert.NotEmpty(t, cmd.Command(test.name))
808 } else {
809 assert.Empty(t, cmd.Command(test.name))
810 }
811 }
812 }
813
814 var defaultCommandTests = []struct {
815 cmdName string
816 defaultCmd string
817 args []string
818 errNotExpected bool
819 }{
820 {"foobar", "foobar", nil, true},
821 {"batbaz", "foobar", nil, true},
822 {"b", "", nil, true},
823 {"f", "", nil, true},
824 {"", "foobar", nil, true},
825 {"", "", nil, true},
826 {" ", "", nil, false},
827 {"bat", "batbaz", nil, true},
828 {"nothing", "batbaz", nil, true},
829 {"nothing", "", nil, false},
830 {"foobar", "foobar", []string{"xy", "zdf"}, true},
831 {"", "foobar", []string{"xy", "zdf"}, true},
832 }
833
834 func TestCommand_RunDefaultCommand(t *testing.T) {
835 for _, test := range defaultCommandTests {
836 testTitle := fmt.Sprintf("command=%[1]s-default=%[2]s-args=%[3]v", test.cmdName, test.defaultCmd, test.args)
837 t.Run(testTitle, func(t *testing.T) {
838 fooCount := 0
839 var fooArgs Args
840 barCount := 0
841 cmd := &Command{
842 DefaultCommand: test.defaultCmd,
843 Commands: []*Command{
844 {
845 Name: "foobar",
846 Aliases: []string{"f"},
847 Action: func(ctx context.Context, c *Command) error {
848 fooCount++
849 fooArgs = c.Args()
850 return nil
851 },
852 },
853 {
854 Name: "batbaz",
855 Aliases: []string{"b"},
856 Action: func(ctx context.Context, c *Command) error {
857 barCount++
858 return nil
859 },
860 },
861 },
862 }
863
864 runArgs := []string{"c"}
865 if test.cmdName != "" {
866 runArgs = append(runArgs, test.cmdName)
867 }
868 if test.args != nil {
869 runArgs = append(runArgs, test.args...)
870 }
871 err := cmd.Run(buildTestContext(t), runArgs)
872 if test.errNotExpected {
873 assert.NoError(t, err)
874 if fooCount == 0 && barCount == 0 && test.defaultCmd != "" {
875 t.Errorf("expected one of the commands to run")
876 }
877 if fooCount > 0 {
878 expectedArgs := &stringSliceArgs{v: []string{}}
879 if len(test.args) > 0 && (test.args[0] == "foobar" || test.args[0] == "f") {
880 expectedArgs = &stringSliceArgs{v: test.args[1:]}
881 } else if test.args != nil {
882 expectedArgs = &stringSliceArgs{v: test.args}
883 }
884 assert.Equal(t, expectedArgs, fooArgs)
885 }
886 } else {
887 if fooCount > 0 || barCount > 0 {
888 t.Errorf("expected no commands to run")
889 }
890 assert.Error(t, err)
891 }
892 })
893 }
894 }
895
896 var defaultCommandSubCommandTests = []struct {
897 cmdName string
898 subCmd string
899 defaultCmd string
900 errNotExpected bool
901 }{
902 {"foobar", "", "foobar", true},
903 {"foobar", "carly", "foobar", true},
904 {"batbaz", "", "foobar", true},
905 {"b", "", "", true},
906 {"f", "", "", true},
907 {"", "", "foobar", true},
908 {"", "", "", true},
909 {"", "jimbob", "foobar", true},
910 {"", "j", "foobar", true},
911 {"", "carly", "foobar", true},
912 {"", "jimmers", "foobar", false},
913 {"", "jimmers", "", false},
914 {" ", "jimmers", "foobar", false},
915 {"", "", "", true},
916 {" ", "", "", false},
917 {" ", "j", "", false},
918 {"bat", "", "batbaz", false},
919 {"nothing", "", "batbaz", false},
920 {"nothing", "", "", false},
921 {"nothing", "j", "batbaz", false},
922 {"nothing", "carly", "", false},
923 }
924
925 func TestCommand_RunDefaultCommandWithSubCommand(t *testing.T) {
926 for _, test := range defaultCommandSubCommandTests {
927 testTitle := fmt.Sprintf("command=%[1]s-subcmd=%[2]s-default=%[3]s", test.cmdName, test.subCmd, test.defaultCmd)
928 t.Run(testTitle, func(t *testing.T) {
929 cmd := &Command{
930 DefaultCommand: test.defaultCmd,
931 Commands: []*Command{
932 {
933 Name: "foobar",
934 Aliases: []string{"f"},
935 Commands: []*Command{
936 {Name: "jimbob", Aliases: []string{"j"}},
937 {Name: "carly"},
938 },
939 },
940 {Name: "batbaz", Aliases: []string{"b"}},
941 },
942 }
943
944 runArgs := []string{"c"}
945 if test.cmdName != "" {
946 runArgs = append(runArgs, test.cmdName)
947 }
948 if test.subCmd != "" {
949 runArgs = append(runArgs, test.subCmd)
950 }
951 err := cmd.Run(buildTestContext(t), runArgs)
952 if test.errNotExpected {
953 assert.NoError(t, err)
954 } else {
955 assert.Error(t, err)
956 }
957 })
958 }
959 }
960
961 var defaultCommandFlagTests = []struct {
962 cmdName string
963 flag string
964 defaultCmd string
965 errNotExpected bool
966 }{
967 {"foobar", "", "foobar", true},
968 {"foobar", "-c derp", "foobar", true},
969 {"batbaz", "", "foobar", true},
970 {"b", "", "", true},
971 {"f", "", "", true},
972 {"", "", "foobar", true},
973 {"", "", "", true},
974 {"", "-j", "foobar", true},
975 {"", "-j", "foobar", true},
976 {"", "-c derp", "foobar", true},
977 {"", "--carly=derp", "foobar", true},
978 {"", "-j", "foobar", true},
979 {"", "-j", "", true},
980 {" ", "-j", "foobar", false},
981 {"", "", "", true},
982 {" ", "", "", false},
983 {" ", "-j", "", false},
984 {"bat", "", "batbaz", false},
985 {"nothing", "", "batbaz", false},
986 {"nothing", "", "", false},
987 {"nothing", "--jimbob", "batbaz", false},
988 {"nothing", "--carly", "", false},
989 }
990
991 func TestCommand_RunDefaultCommandWithFlags(t *testing.T) {
992 for _, test := range defaultCommandFlagTests {
993 testTitle := fmt.Sprintf("command=%[1]s-flag=%[2]s-default=%[3]s", test.cmdName, test.flag, test.defaultCmd)
994 t.Run(testTitle, func(t *testing.T) {
995 cmd := &Command{
996 DefaultCommand: test.defaultCmd,
997 Flags: []Flag{
998 &StringFlag{
999 Name: "carly",
1000 Aliases: []string{"c"},
1001 Required: false,
1002 },
1003 &BoolFlag{
1004 Name: "jimbob",
1005 Aliases: []string{"j"},
1006 Required: false,
1007 Value: true,
1008 },
1009 },
1010 Commands: []*Command{
1011 {
1012 Name: "foobar",
1013 Aliases: []string{"f"},
1014 },
1015 {Name: "batbaz", Aliases: []string{"b"}},
1016 },
1017 }
1018
1019 appArgs := []string{"c"}
1020
1021 if test.flag != "" {
1022 flags := strings.Split(test.flag, " ")
1023 if len(flags) > 1 {
1024 appArgs = append(appArgs, flags...)
1025 }
1026
1027 flags = strings.Split(test.flag, "=")
1028 if len(flags) > 1 {
1029 appArgs = append(appArgs, flags...)
1030 }
1031 }
1032
1033 appArgs = append(appArgs, test.cmdName)
1034
1035 err := cmd.Run(buildTestContext(t), appArgs)
1036 if test.errNotExpected {
1037 assert.NoError(t, err)
1038 } else {
1039 assert.Error(t, err)
1040 }
1041 })
1042 }
1043 }
1044
1045 func TestCommand_FlagsFromExtPackage(t *testing.T) {
1046 var someint int
1047 flag.IntVar(&someint, "epflag", 2, "ext package flag usage")
1048
1049 // Based on source code we can reset the global flag parsing this way
1050 defer func() {
1051 flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
1052 }()
1053
1054 cmd := &Command{
1055 AllowExtFlags: true,
1056 Flags: []Flag{
1057 &StringFlag{
1058 Name: "carly",
1059 Aliases: []string{"c"},
1060 Required: false,
1061 },
1062 &BoolFlag{
1063 Name: "jimbob",
1064 Aliases: []string{"j"},
1065 Required: false,
1066 Value: true,
1067 },
1068 },
1069 }
1070
1071 err := cmd.Run(buildTestContext(t), []string{"foo", "-c", "cly", "--epflag", "10"})
1072 assert.NoError(t, err)
1073
1074 assert.Equal(t, int(10), someint)
1075 // this exercises the extFlag.Get()
1076 assert.Equal(t, int(10), cmd.Value("epflag"))
1077
1078 cmd = &Command{
1079 Flags: []Flag{
1080 &StringFlag{
1081 Name: "carly",
1082 Aliases: []string{"c"},
1083 Required: false,
1084 },
1085 &BoolFlag{
1086 Name: "jimbob",
1087 Aliases: []string{"j"},
1088 Required: false,
1089 Value: true,
1090 },
1091 },
1092 }
1093
1094 // this should return an error since epflag shouldn't be registered
1095 err = cmd.Run(buildTestContext(t), []string{"foo", "-c", "cly", "--epflag", "10"})
1096 assert.Error(t, err)
1097 }
1098
1099 func TestCommand_Setup_defaultsReader(t *testing.T) {
1100 cmd := &Command{}
1101 cmd.setupDefaults([]string{"test"})
1102 assert.Equal(t, cmd.Reader, os.Stdin)
1103 }
1104
1105 func TestCommand_Setup_defaultsWriter(t *testing.T) {
1106 cmd := &Command{}
1107 cmd.setupDefaults([]string{"test"})
1108 assert.Equal(t, cmd.Writer, os.Stdout)
1109 }
1110
1111 func TestCommand_CommandWithFlagBeforeTerminator(t *testing.T) {
1112 var parsedOption string
1113 var args Args
1114
1115 cmd := &Command{
1116 Commands: []*Command{
1117 {
1118 Name: "cmd",
1119 Flags: []Flag{
1120 &StringFlag{Name: "option", Value: "", Usage: "some option"},
1121 },
1122 Action: func(_ context.Context, cmd *Command) error {
1123 parsedOption = cmd.String("option")
1124 args = cmd.Args()
1125 return nil
1126 },
1127 },
1128 },
1129 }
1130
1131 require.NoError(t, cmd.Run(buildTestContext(t), []string{"", "cmd", "--option", "my-option", "my-arg", "--", "--notARealFlag"}))
1132
1133 require.Equal(t, "my-option", parsedOption)
1134 require.Equal(t, "my-arg", args.Get(0))
1135 require.Equal(t, "--notARealFlag", args.Get(1))
1136 }
1137
1138 func TestCommand_CommandWithDash(t *testing.T) {
1139 var args Args
1140
1141 cmd := &Command{
1142 Commands: []*Command{
1143 {
1144 Name: "cmd",
1145 Action: func(_ context.Context, cmd *Command) error {
1146 args = cmd.Args()
1147 return nil
1148 },
1149 },
1150 },
1151 }
1152
1153 require.NoError(t, cmd.Run(buildTestContext(t), []string{"", "cmd", "my-arg", "-"}))
1154 require.NotNil(t, args)
1155 require.Equal(t, "my-arg", args.Get(0))
1156 require.Equal(t, "-", args.Get(1))
1157 }
1158
1159 func TestCommand_CommandWithNoFlagBeforeTerminator(t *testing.T) {
1160 var args Args
1161
1162 cmd := &Command{
1163 Commands: []*Command{
1164 {
1165 Name: "cmd",
1166 Action: func(_ context.Context, cmd *Command) error {
1167 args = cmd.Args()
1168 return nil
1169 },
1170 },
1171 },
1172 }
1173
1174 require.NoError(t, cmd.Run(buildTestContext(t), []string{"", "cmd", "my-arg", "--", "notAFlagAtAll"}))
1175
1176 require.NotNil(t, args)
1177 require.Equal(t, "my-arg", args.Get(0))
1178 require.Equal(t, "notAFlagAtAll", args.Get(1))
1179 }
1180
1181 func TestCommand_SkipFlagParsing(t *testing.T) {
1182 var args Args
1183
1184 cmd := &Command{
1185 SkipFlagParsing: true,
1186 Action: func(_ context.Context, cmd *Command) error {
1187 args = cmd.Args()
1188 return nil
1189 },
1190 }
1191
1192 _ = cmd.Run(buildTestContext(t), []string{"", "--", "my-arg", "notAFlagAtAll"})
1193
1194 assert.NotNil(t, args)
1195 assert.Equal(t, "--", args.Get(0))
1196 assert.Equal(t, "my-arg", args.Get(1))
1197 assert.Equal(t, "notAFlagAtAll", args.Get(2))
1198 }
1199
1200 func TestCommand_VisibleCommands(t *testing.T) {
1201 cmd := &Command{
1202 Commands: []*Command{
1203 {
1204 Name: "frob",
1205 Action: func(context.Context, *Command) error { return nil },
1206 },
1207 {
1208 Name: "frib",
1209 Hidden: true,
1210 Action: func(context.Context, *Command) error { return nil },
1211 },
1212 },
1213 }
1214
1215 cmd.setupDefaults([]string{"test"})
1216 expected := []*Command{
1217 cmd.Commands[0],
1218 }
1219 actual := cmd.VisibleCommands()
1220 assert.Len(t, actual, len(expected))
1221 for i, actualCommand := range actual {
1222 expectedCommand := expected[i]
1223
1224 if expectedCommand.Action != nil {
1225 // comparing func addresses is OK!
1226 assert.Equal(t, fmt.Sprintf("%p", expectedCommand.Action), fmt.Sprintf("%p", actualCommand.Action))
1227 }
1228
1229 func() {
1230 // nil out funcs, as they cannot be compared
1231 // (https://github.com/golang/go/issues/8554)
1232 expectedAction := expectedCommand.Action
1233 actualAction := actualCommand.Action
1234 defer func() {
1235 expectedCommand.Action = expectedAction
1236 actualCommand.Action = actualAction
1237 }()
1238 expectedCommand.Action = nil
1239 actualCommand.Action = nil
1240
1241 assert.Equal(t, expectedCommand, actualCommand)
1242 }()
1243 }
1244 }
1245
1246 func TestCommand_UseShortOptionHandling(t *testing.T) {
1247 var one, two bool
1248 var name string
1249 expected := "expectedName"
1250
1251 cmd := buildMinimalTestCommand()
1252 cmd.UseShortOptionHandling = true
1253 cmd.Flags = []Flag{
1254 &BoolFlag{Name: "one", Aliases: []string{"o"}},
1255 &BoolFlag{Name: "two", Aliases: []string{"t"}},
1256 &StringFlag{Name: "name", Aliases: []string{"n"}},
1257 }
1258 cmd.Action = func(_ context.Context, cmd *Command) error {
1259 one = cmd.Bool("one")
1260 two = cmd.Bool("two")
1261 name = cmd.String("name")
1262 return nil
1263 }
1264
1265 _ = cmd.Run(buildTestContext(t), []string{"", "-on", expected})
1266 assert.True(t, one)
1267 assert.False(t, two)
1268 assert.Equal(t, name, expected)
1269 }
1270
1271 func TestCommand_UseShortOptionHandling_missing_value(t *testing.T) {
1272 cmd := buildMinimalTestCommand()
1273 cmd.UseShortOptionHandling = true
1274 cmd.Flags = []Flag{
1275 &StringFlag{Name: "name", Aliases: []string{"n"}},
1276 }
1277
1278 err := cmd.Run(buildTestContext(t), []string{"", "-n"})
1279 assert.EqualError(t, err, "flag needs an argument: -n")
1280 }
1281
1282 func TestCommand_UseShortOptionHandlingCommand(t *testing.T) {
1283 var (
1284 one, two bool
1285 name string
1286 expected = "expectedName"
1287 )
1288
1289 cmd := &Command{
1290 Name: "cmd",
1291 Flags: []Flag{
1292 &BoolFlag{Name: "one", Aliases: []string{"o"}},
1293 &BoolFlag{Name: "two", Aliases: []string{"t"}},
1294 &StringFlag{Name: "name", Aliases: []string{"n"}},
1295 },
1296 Action: func(_ context.Context, cmd *Command) error {
1297 one = cmd.Bool("one")
1298 two = cmd.Bool("two")
1299 name = cmd.String("name")
1300 return nil
1301 },
1302 UseShortOptionHandling: true,
1303 Writer: io.Discard,
1304 }
1305
1306 require.NoError(t, cmd.Run(buildTestContext(t), []string{"cmd", "-on", expected}))
1307 require.True(t, one)
1308 require.False(t, two)
1309 require.Equal(t, expected, name)
1310 }
1311
1312 func TestCommand_UseShortOptionHandlingCommand_missing_value(t *testing.T) {
1313 cmd := buildMinimalTestCommand()
1314 cmd.UseShortOptionHandling = true
1315 command := &Command{
1316 Name: "cmd",
1317 Flags: []Flag{
1318 &StringFlag{Name: "name", Aliases: []string{"n"}},
1319 },
1320 }
1321 cmd.Commands = []*Command{command}
1322
1323 require.EqualError(
1324 t,
1325 cmd.Run(buildTestContext(t), []string{"", "cmd", "-n"}),
1326 "flag needs an argument: -n",
1327 )
1328 }
1329
1330 func TestCommand_UseShortOptionHandlingSubCommand(t *testing.T) {
1331 var one, two bool
1332 var name string
1333
1334 cmd := buildMinimalTestCommand()
1335 cmd.UseShortOptionHandling = true
1336 cmd.Commands = []*Command{
1337 {
1338 Name: "cmd",
1339 Commands: []*Command{
1340 {
1341 Name: "sub",
1342 Flags: []Flag{
1343 &BoolFlag{Name: "one", Aliases: []string{"o"}},
1344 &BoolFlag{Name: "two", Aliases: []string{"t"}},
1345 &StringFlag{Name: "name", Aliases: []string{"n"}},
1346 },
1347 Action: func(_ context.Context, cmd *Command) error {
1348 one = cmd.Bool("one")
1349 two = cmd.Bool("two")
1350 name = cmd.String("name")
1351 return nil
1352 },
1353 },
1354 },
1355 },
1356 }
1357
1358 expected := "expectedName"
1359
1360 require.NoError(t, cmd.Run(buildTestContext(t), []string{"", "cmd", "sub", "-on", expected}))
1361 require.True(t, one)
1362 require.False(t, two)
1363 require.Equal(t, expected, name)
1364 }
1365
1366 func TestCommand_UseShortOptionHandlingSubCommand_missing_value(t *testing.T) {
1367 cmd := buildMinimalTestCommand()
1368 cmd.UseShortOptionHandling = true
1369 command := &Command{
1370 Name: "cmd",
1371 }
1372 subCommand := &Command{
1373 Name: "sub",
1374 Flags: []Flag{
1375 &StringFlag{Name: "name", Aliases: []string{"n"}},
1376 },
1377 }
1378 command.Commands = []*Command{subCommand}
1379 cmd.Commands = []*Command{command}
1380
1381 err := cmd.Run(buildTestContext(t), []string{"", "cmd", "sub", "-n"})
1382 assert.EqualError(t, err, "flag needs an argument: -n")
1383 }
1384
1385 func TestCommand_UseShortOptionAfterSliceFlag(t *testing.T) {
1386 var one, two bool
1387 var name string
1388 var sliceValDest []string
1389 var sliceVal []string
1390 expected := "expectedName"
1391
1392 cmd := buildMinimalTestCommand()
1393 cmd.UseShortOptionHandling = true
1394 cmd.Flags = []Flag{
1395 &StringSliceFlag{Name: "env", Aliases: []string{"e"}, Destination: &sliceValDest},
1396 &BoolFlag{Name: "one", Aliases: []string{"o"}},
1397 &BoolFlag{Name: "two", Aliases: []string{"t"}},
1398 &StringFlag{Name: "name", Aliases: []string{"n"}},
1399 }
1400 cmd.Action = func(_ context.Context, cmd *Command) error {
1401 sliceVal = cmd.StringSlice("env")
1402 one = cmd.Bool("one")
1403 two = cmd.Bool("two")
1404 name = cmd.String("name")
1405 return nil
1406 }
1407
1408 _ = cmd.Run(buildTestContext(t), []string{"", "-e", "foo", "-on", expected})
1409 assert.Equal(t, sliceVal, []string{"foo"})
1410 assert.Equal(t, sliceValDest, []string{"foo"})
1411 assert.True(t, one)
1412 assert.False(t, two)
1413 assert.Equal(t, expected, name)
1414 }
1415
1416 func TestCommand_UseShortOptionWithArg(t *testing.T) {
1417 var rootPath string
1418 cmd := &Command{
1419 UseShortOptionHandling: true,
1420 Commands: []*Command{
1421 {
1422 Name: "short",
1423 Usage: "complete a task on the list",
1424 Arguments: []Argument{
1425 &StringArg{Name: "root", UsageText: "Root path", Destination: &rootPath},
1426 },
1427 Flags: []Flag{
1428 &BoolFlag{Name: "serve", Aliases: []string{"s"}},
1429 &BoolFlag{Name: "option", Aliases: []string{"o"}},
1430 &StringFlag{Name: "message", Aliases: []string{"m"}},
1431 },
1432 Action: func(ctx context.Context, cmd *Command) error {
1433 return nil
1434 },
1435 },
1436 },
1437 }
1438 err := cmd.Run(buildTestContext(t), []string{"app", "short", "-som", "hello", "/path/to/root"})
1439 require.NoError(t, err)
1440 require.Equal(t, "/path/to/root", rootPath)
1441 }
1442
1443 func TestCommand_Float64Flag(t *testing.T) {
1444 var meters float64
1445
1446 cmd := &Command{
1447 Flags: []Flag{
1448 &FloatFlag{Name: "height", Value: 1.5, Usage: "Set the height, in meters"},
1449 },
1450 Action: func(_ context.Context, cmd *Command) error {
1451 meters = cmd.Float("height")
1452 return nil
1453 },
1454 }
1455
1456 _ = cmd.Run(buildTestContext(t), []string{"", "--height", "1.93"})
1457 assert.Equal(t, 1.93, meters)
1458 }
1459
1460 func TestCommand_ParseSliceFlags(t *testing.T) {
1461 var parsedIntSlice []int64
1462 var parsedStringSlice []string
1463
1464 cmd := &Command{
1465 Commands: []*Command{
1466 {
1467 Name: "cmd",
1468 Flags: []Flag{
1469 &Int64SliceFlag{Name: "p", Value: []int64{}, Usage: "set one or more ip addr"},
1470 &StringSliceFlag{Name: "ip", Value: []string{}, Usage: "set one or more ports to open"},
1471 },
1472 Action: func(_ context.Context, cmd *Command) error {
1473 parsedIntSlice = cmd.Int64Slice("p")
1474 parsedStringSlice = cmd.StringSlice("ip")
1475 return nil
1476 },
1477 },
1478 },
1479 }
1480
1481 r := require.New(t)
1482
1483 r.NoError(cmd.Run(buildTestContext(t), []string{"", "cmd", "-p", "22", "-p", "80", "-ip", "8.8.8.8", "-ip", "8.8.4.4"}))
1484 r.Equal([]int64{22, 80}, parsedIntSlice)
1485 r.Equal([]string{"8.8.8.8", "8.8.4.4"}, parsedStringSlice)
1486 }
1487
1488 func TestCommand_ParseSliceFlagsWithMissingValue(t *testing.T) {
1489 var parsedIntSlice []int64
1490 var parsedStringSlice []string
1491
1492 cmd := &Command{
1493 Commands: []*Command{
1494 {
1495 Name: "cmd",
1496 Flags: []Flag{
1497 &Int64SliceFlag{Name: "a", Usage: "set numbers"},
1498 &StringSliceFlag{Name: "str", Usage: "set strings"},
1499 },
1500 Action: func(_ context.Context, cmd *Command) error {
1501 parsedIntSlice = cmd.Int64Slice("a")
1502 parsedStringSlice = cmd.StringSlice("str")
1503 return nil
1504 },
1505 },
1506 },
1507 }
1508
1509 r := require.New(t)
1510
1511 r.NoError(cmd.Run(buildTestContext(t), []string{"", "cmd", "-a", "2", "-str", "A"}))
1512 r.Equal([]int64{2}, parsedIntSlice)
1513 r.Equal([]string{"A"}, parsedStringSlice)
1514 }
1515
1516 func TestCommand_DefaultStdin(t *testing.T) {
1517 cmd := &Command{}
1518 cmd.setupDefaults([]string{"test"})
1519
1520 assert.Equal(t, cmd.Reader, os.Stdin, "Default input reader not set.")
1521 }
1522
1523 func TestCommand_DefaultStdout(t *testing.T) {
1524 cmd := &Command{}
1525 cmd.setupDefaults([]string{"test"})
1526
1527 assert.Equal(t, cmd.Writer, os.Stdout, "Default output writer not set.")
1528 }
1529
1530 func TestCommand_SetStdin(t *testing.T) {
1531 buf := make([]byte, 12)
1532
1533 cmd := &Command{
1534 Name: "test",
1535 Reader: strings.NewReader("Hello World!"),
1536 Action: func(_ context.Context, cmd *Command) error {
1537 _, err := cmd.Reader.Read(buf)
1538 return err
1539 },
1540 }
1541
1542 err := cmd.Run(buildTestContext(t), []string{"help"})
1543 require.NoError(t, err)
1544 assert.Equal(t, "Hello World!", string(buf), "Command did not read input from desired reader.")
1545 }
1546
1547 func TestCommand_SetStdin_Subcommand(t *testing.T) {
1548 buf := make([]byte, 12)
1549
1550 cmd := &Command{
1551 Name: "test",
1552 Reader: strings.NewReader("Hello World!"),
1553 Commands: []*Command{
1554 {
1555 Name: "command",
1556 Commands: []*Command{
1557 {
1558 Name: "subcommand",
1559 Action: func(_ context.Context, cmd *Command) error {
1560 _, err := cmd.Root().Reader.Read(buf)
1561 return err
1562 },
1563 },
1564 },
1565 },
1566 },
1567 }
1568
1569 err := cmd.Run(buildTestContext(t), []string{"test", "command", "subcommand"})
1570 require.NoError(t, err)
1571 assert.Equal(t, "Hello World!", string(buf), "Command did not read input from desired reader.")
1572 }
1573
1574 func TestCommand_SetStdout(t *testing.T) {
1575 var w bytes.Buffer
1576
1577 cmd := &Command{
1578 Name: "test",
1579 Writer: &w,
1580 }
1581
1582 err := cmd.Run(buildTestContext(t), []string{"help"})
1583 require.NoError(t, err)
1584 assert.NotZero(t, w.Len(), "Command did not write output to desired writer.")
1585 }
1586
1587 func TestCommand_BeforeFunc(t *testing.T) {
1588 counts := &opCounts{}
1589 beforeError := fmt.Errorf("fail")
1590 var err error
1591
1592 cmd := &Command{
1593 Before: func(_ context.Context, cmd *Command) (context.Context, error) {
1594 counts.Total++
1595 counts.Before = counts.Total
1596 s := cmd.String("opt")
1597 if s == "fail" {
1598 return nil, beforeError
1599 }
1600
1601 return nil, nil
1602 },
1603 Commands: []*Command{
1604 {
1605 Name: "sub",
1606 Action: func(context.Context, *Command) error {
1607 counts.Total++
1608 counts.SubCommand = counts.Total
1609 return nil
1610 },
1611 },
1612 },
1613 Flags: []Flag{
1614 &StringFlag{Name: "opt"},
1615 },
1616 Writer: io.Discard,
1617 }
1618
1619 // run with the Before() func succeeding
1620 err = cmd.Run(buildTestContext(t), []string{"command", "--opt", "succeed", "sub"})
1621 require.NoError(t, err)
1622
1623 assert.Equal(t, 1, counts.Before, "Before() not executed when expected")
1624 assert.Equal(t, 2, counts.SubCommand, "Subcommand not executed when expected")
1625
1626 // reset
1627 counts = &opCounts{}
1628
1629 // run with the Before() func failing
1630 err = cmd.Run(buildTestContext(t), []string{"command", "--opt", "fail", "sub"})
1631
1632 // should be the same error produced by the Before func
1633 assert.ErrorIs(t, err, beforeError, "Run error expected, but not received")
1634 assert.Equal(t, 1, counts.Before, "Before() not executed when expected")
1635 assert.Equal(t, 0, counts.SubCommand, "Subcommand executed when NOT expected")
1636
1637 // reset
1638 counts = &opCounts{}
1639
1640 afterError := errors.New("fail again")
1641 cmd.After = func(context.Context, *Command) error {
1642 return afterError
1643 }
1644
1645 // run with the Before() func failing, wrapped by After()
1646 err = cmd.Run(buildTestContext(t), []string{"command", "--opt", "fail", "sub"})
1647
1648 // should be the same error produced by the Before func
1649 if _, ok := err.(MultiError); !ok {
1650 t.Errorf("MultiError expected, but not received")
1651 }
1652
1653 assert.Equal(t, 1, counts.Before, "Before() not executed when expected")
1654 assert.Zero(t, counts.SubCommand, "Subcommand executed when NOT expected")
1655 }
1656
1657 func TestCommand_BeforeFuncPersistentFlag(t *testing.T) {
1658 counts := &opCounts{}
1659 beforeError := fmt.Errorf("fail")
1660 var err error
1661
1662 cmd := &Command{
1663 Before: func(_ context.Context, cmd *Command) (context.Context, error) {
1664 counts.Before++
1665 s := cmd.String("opt")
1666 if s != "value" {
1667 return nil, beforeError
1668 }
1669 return nil, nil
1670 },
1671 Commands: []*Command{
1672 {
1673 Name: "sub",
1674 Action: func(context.Context, *Command) error {
1675 counts.SubCommand++
1676 return nil
1677 },
1678 },
1679 },
1680 Flags: []Flag{
1681 &StringFlag{Name: "opt"},
1682 },
1683 Writer: io.Discard,
1684 }
1685
1686 // Check that --opt value is available in root command Before hook,
1687 // even when it was set on the subcommand.
1688 err = cmd.Run(buildTestContext(t), []string{"command", "sub", "--opt", "value"})
1689 require.NoError(t, err)
1690 assert.Equal(t, 1, counts.Before, "Before() not executed when expected")
1691 assert.Equal(t, 1, counts.SubCommand, "Subcommand not executed when expected")
1692 }
1693
1694 func TestCommand_BeforeAfterFuncShellCompletion(t *testing.T) {
1695 t.Skip("TODO: is '--generate-shell-completion' (flag) still supported?")
1696
1697 counts := &opCounts{}
1698
1699 cmd := &Command{
1700 EnableShellCompletion: true,
1701 Before: func(context.Context, *Command) (context.Context, error) {
1702 counts.Total++
1703 counts.Before = counts.Total
1704 return nil, nil
1705 },
1706 After: func(context.Context, *Command) error {
1707 counts.Total++
1708 counts.After = counts.Total
1709 return nil
1710 },
1711 Commands: []*Command{
1712 {
1713 Name: "sub",
1714 Action: func(context.Context, *Command) error {
1715 counts.Total++
1716 counts.SubCommand = counts.Total
1717 return nil
1718 },
1719 },
1720 },
1721 Flags: []Flag{
1722 &StringFlag{Name: "opt"},
1723 },
1724 Writer: io.Discard,
1725 }
1726
1727 r := require.New(t)
1728
1729 // run with the Before() func succeeding
1730 r.NoError(
1731 cmd.Run(
1732 buildTestContext(t),
1733 []string{
1734 "command",
1735 "--opt", "succeed",
1736 "sub", completionFlag,
1737 },
1738 ),
1739 )
1740
1741 r.Equalf(0, counts.Before, "Before was run")
1742 r.Equal(0, counts.After, "After was run")
1743 r.Equal(0, counts.SubCommand, "SubCommand was run")
1744 }
1745
1746 func TestCommand_AfterFunc(t *testing.T) {
1747 counts := &opCounts{}
1748 afterError := fmt.Errorf("fail")
1749 var err error
1750
1751 cmd := &Command{
1752 After: func(_ context.Context, cmd *Command) error {
1753 counts.Total++
1754 counts.After = counts.Total
1755 s := cmd.String("opt")
1756 if s == "fail" {
1757 return afterError
1758 }
1759
1760 return nil
1761 },
1762 Commands: []*Command{
1763 {
1764 Name: "sub",
1765 Action: func(context.Context, *Command) error {
1766 counts.Total++
1767 counts.SubCommand = counts.Total
1768 return nil
1769 },
1770 },
1771 },
1772 Flags: []Flag{
1773 &StringFlag{Name: "opt"},
1774 },
1775 }
1776
1777 // run with the After() func succeeding
1778 err = cmd.Run(buildTestContext(t), []string{"command", "--opt", "succeed", "sub"})
1779 require.NoError(t, err)
1780 assert.Equal(t, 2, counts.After, "After() not executed when expected")
1781 assert.Equal(t, 1, counts.SubCommand, "Subcommand not executed when expected")
1782
1783 // reset
1784 counts = &opCounts{}
1785
1786 // run with the Before() func failing
1787 err = cmd.Run(buildTestContext(t), []string{"command", "--opt", "fail", "sub"})
1788
1789 // should be the same error produced by the Before func
1790 assert.ErrorIs(t, err, afterError, "Run error expected, but not received")
1791 assert.Equal(t, 2, counts.After, "After() not executed when expected")
1792 assert.Equal(t, 1, counts.SubCommand, "Subcommand not executed when expected")
1793
1794 /*
1795 reset
1796 */
1797 counts = &opCounts{}
1798 // reset the flags since they are set previously
1799 cmd.Flags = []Flag{
1800 &StringFlag{Name: "opt"},
1801 }
1802
1803 // run with none args
1804 err = cmd.Run(buildTestContext(t), []string{"command"})
1805
1806 // should be the same error produced by the Before func
1807 require.NoError(t, err)
1808
1809 assert.Equal(t, 1, counts.After, "After() not executed when expected")
1810 assert.Equal(t, 0, counts.SubCommand, "Subcommand not executed when expected")
1811 }
1812
1813 func TestCommand_AfterNotCalledOnSubcommandHelp(t *testing.T) {
1814 var afterCalled bool
1815 cmd := &Command{
1816 After: func(_ context.Context, _ *Command) error {
1817 afterCalled = true
1818 return nil
1819 },
1820 Commands: []*Command{
1821 {
1822 Name: "sub",
1823 Action: func(context.Context, *Command) error {
1824 return nil
1825 },
1826 },
1827 },
1828 }
1829
1830 err := cmd.Run(buildTestContext(t), []string{"app", "sub", "--help"})
1831 require.NoError(t, err)
1832 assert.False(t, afterCalled, "After should not be called when --help is passed to subcommand")
1833 }
1834
1835 func TestCommand_AfterStillCalledOnNormalSubcommand(t *testing.T) {
1836 var afterCalled bool
1837 cmd := &Command{
1838 After: func(_ context.Context, _ *Command) error {
1839 afterCalled = true
1840 return nil
1841 },
1842 Commands: []*Command{
1843 {
1844 Name: "sub",
1845 Action: func(context.Context, *Command) error {
1846 return nil
1847 },
1848 },
1849 },
1850 }
1851
1852 err := cmd.Run(buildTestContext(t), []string{"app", "sub"})
1853 require.NoError(t, err)
1854 assert.True(t, afterCalled, "After should be called on normal subcommand execution")
1855 }
1856
1857 func TestCommandNoHelpFlag(t *testing.T) {
1858 oldFlag := HelpFlag
1859 defer func() {
1860 HelpFlag = oldFlag
1861 }()
1862
1863 HelpFlag = nil
1864
1865 cmd := &Command{Writer: io.Discard}
1866
1867 err := cmd.Run(buildTestContext(t), []string{"test", "-h"})
1868
1869 assert.ErrorContains(t, err, providedButNotDefinedErrMsg, "expected error about missing help flag")
1870 }
1871
1872 func TestRequiredFlagCommandRunBehavior(t *testing.T) {
1873 tdata := []struct {
1874 testCase string
1875 appFlags []Flag
1876 appRunInput []string
1877 appCommands []*Command
1878 expectedAnError bool
1879 }{
1880 // assertion: empty input, when a required flag is present, errors
1881 {
1882 testCase: "error_case_empty_input_with_required_flag_on_app",
1883 appRunInput: []string{"myCLI"},
1884 appFlags: []Flag{&StringFlag{Name: "requiredFlag", Required: true}},
1885 expectedAnError: true,
1886 },
1887 {
1888 testCase: "error_case_empty_input_with_required_flag_on_command",
1889 appRunInput: []string{"myCLI", "myCommand"},
1890 appCommands: []*Command{{
1891 Name: "myCommand",
1892 Flags: []Flag{&StringFlag{Name: "requiredFlag", Required: true}},
1893 }},
1894 expectedAnError: true,
1895 },
1896 {
1897 testCase: "error_case_empty_input_with_required_flag_on_subcommand",
1898 appRunInput: []string{"myCLI", "myCommand", "mySubCommand"},
1899 appCommands: []*Command{{
1900 Name: "myCommand",
1901 Commands: []*Command{{
1902 Name: "mySubCommand",
1903 Flags: []Flag{&StringFlag{Name: "requiredFlag", Required: true}},
1904 }},
1905 }},
1906 expectedAnError: true,
1907 },
1908 // assertion: inputting --help, when a required flag is present, does not error
1909 {
1910 testCase: "valid_case_help_input_with_required_flag_on_app",
1911 appRunInput: []string{"myCLI", "--help"},
1912 appFlags: []Flag{&StringFlag{Name: "requiredFlag", Required: true}},
1913 },
1914 {
1915 testCase: "valid_case_help_input_with_required_flag_on_command",
1916 appRunInput: []string{"myCLI", "myCommand", "--help"},
1917 appCommands: []*Command{{
1918 Name: "myCommand",
1919 Flags: []Flag{&StringFlag{Name: "requiredFlag", Required: true}},
1920 }},
1921 },
1922 {
1923 testCase: "valid_case_help_input_with_required_flag_on_subcommand",
1924 appRunInput: []string{"myCLI", "myCommand", "mySubCommand", "--help"},
1925 appCommands: []*Command{{
1926 Name: "myCommand",
1927 Commands: []*Command{{
1928 Name: "mySubCommand",
1929 Flags: []Flag{&StringFlag{Name: "requiredFlag", Required: true}},
1930 }},
1931 }},
1932 },
1933 // assertion: giving optional input, when a required flag is present, errors
1934 {
1935 testCase: "error_case_optional_input_with_required_flag_on_app",
1936 appRunInput: []string{"myCLI", "--optional", "cats"},
1937 appFlags: []Flag{&StringFlag{Name: "requiredFlag", Required: true}, &StringFlag{Name: "optional"}},
1938 expectedAnError: true,
1939 },
1940 {
1941 testCase: "error_case_optional_input_with_required_flag_on_command",
1942 appRunInput: []string{"myCLI", "myCommand", "--optional", "cats"},
1943 appCommands: []*Command{{
1944 Name: "myCommand",
1945 Flags: []Flag{&StringFlag{Name: "requiredFlag", Required: true}, &StringFlag{Name: "optional"}},
1946 }},
1947 expectedAnError: true,
1948 },
1949 {
1950 testCase: "error_case_optional_input_with_required_flag_on_subcommand",
1951 appRunInput: []string{"myCLI", "myCommand", "mySubCommand", "--optional", "cats"},
1952 appCommands: []*Command{{
1953 Name: "myCommand",
1954 Commands: []*Command{{
1955 Name: "mySubCommand",
1956 Flags: []Flag{&StringFlag{Name: "requiredFlag", Required: true}, &StringFlag{Name: "optional"}},
1957 }},
1958 }},
1959 expectedAnError: true,
1960 },
1961 // assertion: when a required flag is present, inputting that required flag does not error
1962 {
1963 testCase: "valid_case_required_flag_input_on_app",
1964 appRunInput: []string{"myCLI", "--requiredFlag", "cats"},
1965 appFlags: []Flag{&StringFlag{Name: "requiredFlag", Required: true}},
1966 },
1967 {
1968 testCase: "valid_case_required_flag_input_on_command",
1969 appRunInput: []string{"myCLI", "myCommand", "--requiredFlag", "cats"},
1970 appCommands: []*Command{{
1971 Name: "myCommand",
1972 Flags: []Flag{&StringFlag{Name: "requiredFlag", Required: true}},
1973 }},
1974 },
1975 {
1976 testCase: "valid_case_required_flag_input_on_subcommand",
1977 appRunInput: []string{"myCLI", "myCommand", "mySubCommand", "--requiredFlag", "cats"},
1978 appCommands: []*Command{{
1979 Name: "myCommand",
1980 Commands: []*Command{{
1981 Name: "mySubCommand",
1982 Flags: []Flag{&StringFlag{Name: "requiredFlag", Required: true}},
1983 Action: func(context.Context, *Command) error {
1984 return nil
1985 },
1986 }},
1987 }},
1988 },
1989 }
1990 for _, test := range tdata {
1991 t.Run(test.testCase, func(t *testing.T) {
1992 // setup
1993 cmd := buildMinimalTestCommand()
1994 cmd.Flags = test.appFlags
1995 cmd.Commands = test.appCommands
1996
1997 // logic under test
1998 err := cmd.Run(buildTestContext(t), test.appRunInput)
1999
2000 // assertions
2001 if test.expectedAnError {
2002 assert.Error(t, err)
2003 if _, ok := err.(requiredFlagsErr); test.expectedAnError && !ok {
2004 t.Errorf("expected a requiredFlagsErr, but got: %s", err)
2005 }
2006 } else {
2007 assert.NoError(t, err)
2008 }
2009 })
2010 }
2011 }
2012
2013 func TestCommand_IncorrectUsageOnRequiredFlagsViaRun(t *testing.T) {
2014 t.Run("root command missing required flag", func(t *testing.T) {
2015 r := require.New(t)
2016 var buf bytes.Buffer
2017 var errBuf bytes.Buffer
2018
2019 cmd := &Command{
2020 Writer: &buf,
2021 ErrWriter: &errBuf,
2022 Flags: []Flag{
2023 &StringFlag{Name: "requiredFlag", Required: true},
2024 },
2025 }
2026
2027 _ = cmd.Run(buildTestContext(t), []string{"command"})
2028 r.Contains(errBuf.String(), "Incorrect Usage")
2029 r.Contains(buf.String(), "NAME:")
2030 r.Contains(buf.String(), "command")
2031 })
2032
2033 t.Run("subcommand missing required flag", func(t *testing.T) {
2034 r := require.New(t)
2035 var buf bytes.Buffer
2036 var errBuf bytes.Buffer
2037
2038 cmd := &Command{
2039 Writer: &buf,
2040 ErrWriter: &errBuf,
2041 Commands: []*Command{
2042 {
2043 Name: "sub",
2044 Flags: []Flag{
2045 &StringFlag{Name: "requiredFlag", Required: true},
2046 },
2047 Action: func(ctx context.Context, cmd *Command) error {
2048 return nil
2049 },
2050 },
2051 },
2052 }
2053
2054 _ = cmd.Run(buildTestContext(t), []string{"command", "sub"})
2055 r.Contains(errBuf.String(), "Incorrect Usage")
2056 r.Contains(buf.String(), "NAME:")
2057 r.Contains(buf.String(), "sub")
2058 })
2059 }
2060
2061 func TestCommand_IncorrectUsageOnMutuallyExclusiveFlagsViaRun(t *testing.T) {
2062 t.Run("root command with mutex violation", func(t *testing.T) {
2063 r := require.New(t)
2064 var buf bytes.Buffer
2065 var errBuf bytes.Buffer
2066
2067 cmd := &Command{
2068 Writer: &buf,
2069 ErrWriter: &errBuf,
2070 MutuallyExclusiveFlags: []MutuallyExclusiveFlags{
2071 {
2072 Flags: [][]Flag{
2073 {&StringFlag{Name: "foo1"}},
2074 {&StringFlag{Name: "foo2"}},
2075 },
2076 },
2077 },
2078 }
2079
2080 _ = cmd.Run(buildTestContext(t), []string{"command", "--foo1", "v1", "--foo2", "v2"})
2081 r.Contains(errBuf.String(), "Incorrect Usage")
2082 r.Contains(buf.String(), "NAME:")
2083 r.Contains(buf.String(), "command")
2084 })
2085
2086 t.Run("subcommand with mutex violation", func(t *testing.T) {
2087 r := require.New(t)
2088 var buf bytes.Buffer
2089 var errBuf bytes.Buffer
2090
2091 cmd := &Command{
2092 Writer: &buf,
2093 ErrWriter: &errBuf,
2094 Action: func(ctx context.Context, cmd *Command) error {
2095 return nil
2096 },
2097 Commands: []*Command{
2098 {
2099 Name: "sub",
2100 MutuallyExclusiveFlags: []MutuallyExclusiveFlags{
2101 {
2102 Flags: [][]Flag{
2103 {&StringFlag{Name: "foo1"}},
2104 {&StringFlag{Name: "foo2"}},
2105 },
2106 },
2107 },
2108 },
2109 },
2110 }
2111
2112 _ = cmd.Run(buildTestContext(t), []string{"command", "sub", "--foo1", "v1", "--foo2", "v2"})
2113 r.Contains(errBuf.String(), "Incorrect Usage")
2114 r.Contains(buf.String(), "NAME:")
2115 r.Contains(buf.String(), "sub")
2116 })
2117 }
2118
2119 func TestCommand_IncorrectUsageOnSubcommandWithFailingShowCommandHelp(t *testing.T) {
2120 t.Run("required flags fallback to ShowSubcommandHelp", func(t *testing.T) {
2121 oldShowCommandHelp := ShowCommandHelp
2122 defer func() { ShowCommandHelp = oldShowCommandHelp }()
2123 ShowCommandHelp = func(_ context.Context, _ *Command, _ string) error {
2124 return errors.New("forced error")
2125 }
2126
2127 r := require.New(t)
2128 var buf bytes.Buffer
2129 var errBuf bytes.Buffer
2130
2131 cmd := &Command{
2132 Writer: &buf,
2133 ErrWriter: &errBuf,
2134 Commands: []*Command{
2135 {
2136 Name: "sub",
2137 Flags: []Flag{
2138 &StringFlag{Name: "requiredFlag", Required: true},
2139 },
2140 Action: func(ctx context.Context, cmd *Command) error {
2141 return nil
2142 },
2143 },
2144 },
2145 }
2146
2147 _ = cmd.Run(buildTestContext(t), []string{"command", "sub"})
2148 r.Contains(errBuf.String(), "Incorrect Usage")
2149 r.Contains(buf.String(), "sub")
2150 })
2151
2152 t.Run("mutex flags fallback to ShowSubcommandHelp", func(t *testing.T) {
2153 oldShowCommandHelp := ShowCommandHelp
2154 defer func() { ShowCommandHelp = oldShowCommandHelp }()
2155 ShowCommandHelp = func(_ context.Context, _ *Command, _ string) error {
2156 return errors.New("forced error")
2157 }
2158
2159 r := require.New(t)
2160 var buf bytes.Buffer
2161 var errBuf bytes.Buffer
2162
2163 cmd := &Command{
2164 Writer: &buf,
2165 ErrWriter: &errBuf,
2166 Action: func(ctx context.Context, cmd *Command) error {
2167 return nil
2168 },
2169 Commands: []*Command{
2170 {
2171 Name: "sub",
2172 MutuallyExclusiveFlags: []MutuallyExclusiveFlags{
2173 {
2174 Flags: [][]Flag{
2175 {&StringFlag{Name: "foo1"}},
2176 {&StringFlag{Name: "foo2"}},
2177 },
2178 },
2179 },
2180 },
2181 },
2182 }
2183
2184 _ = cmd.Run(buildTestContext(t), []string{"command", "sub", "--foo1", "v1", "--foo2", "v2"})
2185 r.Contains(errBuf.String(), "Incorrect Usage")
2186 r.Contains(buf.String(), "sub")
2187 })
2188 }
2189
2190 func TestCommandHelpPrinter(t *testing.T) {
2191 oldPrinter := HelpPrinter
2192 defer func() {
2193 HelpPrinter = oldPrinter
2194 }()
2195
2196 wasCalled := false
2197 HelpPrinter = func(io.Writer, string, any) {
2198 wasCalled = true
2199 }
2200
2201 cmd := &Command{}
2202
2203 _ = cmd.Run(buildTestContext(t), []string{"-h"})
2204
2205 assert.True(t, wasCalled, "Help printer expected to be called, but was not")
2206 }
2207
2208 func TestCommand_VersionPrinter(t *testing.T) {
2209 oldPrinter := VersionPrinter
2210 defer func() {
2211 VersionPrinter = oldPrinter
2212 }()
2213
2214 wasCalled := false
2215 VersionPrinter = func(*Command) {
2216 wasCalled = true
2217 }
2218
2219 cmd := &Command{}
2220 ShowVersion(cmd)
2221
2222 assert.True(t, wasCalled, "Version printer expected to be called, but was not")
2223 }
2224
2225 func TestCommand_CommandNotFound(t *testing.T) {
2226 counts := &opCounts{}
2227 cmd := &Command{
2228 CommandNotFound: func(context.Context, *Command, string) {
2229 counts.Total++
2230 counts.CommandNotFound = counts.Total
2231 },
2232 Commands: []*Command{
2233 {
2234 Name: "bar",
2235 Action: func(context.Context, *Command) error {
2236 counts.Total++
2237 counts.SubCommand = counts.Total
2238 return nil
2239 },
2240 },
2241 },
2242 }
2243
2244 _ = cmd.Run(buildTestContext(t), []string{"command", "foo"})
2245
2246 assert.Equal(t, 1, counts.CommandNotFound)
2247 assert.Equal(t, 0, counts.SubCommand)
2248 assert.Equal(t, 1, counts.Total)
2249 }
2250
2251 func TestCommand_OrderOfOperations(t *testing.T) {
2252 buildCmdCounts := func() (*Command, *opCounts) {
2253 counts := &opCounts{}
2254
2255 cmd := &Command{
2256 EnableShellCompletion: true,
2257 ShellComplete: func(context.Context, *Command) {
2258 counts.Total++
2259 counts.ShellComplete = counts.Total
2260 },
2261 OnUsageError: func(context.Context, *Command, error, bool) error {
2262 counts.Total++
2263 counts.OnUsageError = counts.Total
2264 return errors.New("hay OnUsageError")
2265 },
2266 Writer: io.Discard,
2267 }
2268
2269 beforeNoError := func(context.Context, *Command) (context.Context, error) {
2270 counts.Total++
2271 counts.Before = counts.Total
2272 return nil, nil
2273 }
2274
2275 cmd.Before = beforeNoError
2276 cmd.CommandNotFound = func(context.Context, *Command, string) {
2277 counts.Total++
2278 counts.CommandNotFound = counts.Total
2279 }
2280
2281 afterNoError := func(context.Context, *Command) error {
2282 counts.Total++
2283 counts.After = counts.Total
2284 return nil
2285 }
2286
2287 cmd.After = afterNoError
2288 cmd.Commands = []*Command{
2289 {
2290 Name: "bar",
2291 Action: func(context.Context, *Command) error {
2292 counts.Total++
2293 counts.SubCommand = counts.Total
2294 return nil
2295 },
2296 },
2297 }
2298
2299 cmd.Action = func(context.Context, *Command) error {
2300 counts.Total++
2301 counts.Action = counts.Total
2302 return nil
2303 }
2304
2305 return cmd, counts
2306 }
2307
2308 t.Run("on usage error", func(t *testing.T) {
2309 cmd, counts := buildCmdCounts()
2310 r := require.New(t)
2311
2312 _ = cmd.Run(buildTestContext(t), []string{"command", "--nope"})
2313 r.Equal(1, counts.OnUsageError)
2314 r.Equal(1, counts.Total)
2315 })
2316
2317 t.Run("shell complete", func(t *testing.T) {
2318 cmd, counts := buildCmdCounts()
2319 r := require.New(t)
2320
2321 _ = cmd.Run(buildTestContext(t), []string{"command", completionFlag})
2322 r.Equal(1, counts.Before)
2323 r.Equal(2, counts.ShellComplete)
2324 r.Equal(2, counts.Total)
2325 })
2326
2327 t.Run("nil on usage error", func(t *testing.T) {
2328 cmd, counts := buildCmdCounts()
2329 cmd.OnUsageError = nil
2330
2331 _ = cmd.Run(buildTestContext(t), []string{"command", "--nope"})
2332 require.Equal(t, 0, counts.Total)
2333 })
2334
2335 t.Run("before after action hooks", func(t *testing.T) {
2336 cmd, counts := buildCmdCounts()
2337 r := require.New(t)
2338
2339 _ = cmd.Run(buildTestContext(t), []string{"command", "foo"})
2340 r.Equal(0, counts.OnUsageError)
2341 r.Equal(1, counts.Before)
2342 r.Equal(0, counts.CommandNotFound)
2343 r.Equal(2, counts.Action)
2344 r.Equal(3, counts.After)
2345 r.Equal(3, counts.Total)
2346 })
2347
2348 t.Run("before with error", func(t *testing.T) {
2349 cmd, counts := buildCmdCounts()
2350 cmd.Before = func(context.Context, *Command) (context.Context, error) {
2351 counts.Total++
2352 counts.Before = counts.Total
2353 return nil, errors.New("hay Before")
2354 }
2355
2356 r := require.New(t)
2357
2358 _ = cmd.Run(buildTestContext(t), []string{"command", "bar"})
2359 r.Equal(0, counts.OnUsageError)
2360 r.Equal(1, counts.Before)
2361 r.Equal(2, counts.After)
2362 r.Equal(2, counts.Total)
2363 })
2364
2365 t.Run("nil after", func(t *testing.T) {
2366 cmd, counts := buildCmdCounts()
2367 cmd.After = nil
2368 r := require.New(t)
2369
2370 _ = cmd.Run(buildTestContext(t), []string{"command", "bar"})
2371 r.Equal(0, counts.OnUsageError)
2372 r.Equal(1, counts.Before)
2373 r.Equal(2, counts.SubCommand)
2374 r.Equal(2, counts.Total)
2375 })
2376
2377 t.Run("after errors", func(t *testing.T) {
2378 cmd, counts := buildCmdCounts()
2379 cmd.After = func(context.Context, *Command) error {
2380 counts.Total++
2381 counts.After = counts.Total
2382 return errors.New("hay After")
2383 }
2384
2385 r := require.New(t)
2386
2387 err := cmd.Run(buildTestContext(t), []string{"command", "bar"})
2388 r.Error(err)
2389 r.Equal(0, counts.OnUsageError)
2390 r.Equal(1, counts.Before)
2391 r.Equal(2, counts.SubCommand)
2392 r.Equal(3, counts.After)
2393 r.Equal(3, counts.Total)
2394 })
2395
2396 t.Run("nil commands", func(t *testing.T) {
2397 cmd, counts := buildCmdCounts()
2398 cmd.Commands = nil
2399 r := require.New(t)
2400
2401 _ = cmd.Run(buildTestContext(t), []string{"command"})
2402 r.Equal(0, counts.OnUsageError)
2403 r.Equal(1, counts.Before)
2404 r.Equal(2, counts.Action)
2405 r.Equal(3, counts.After)
2406 r.Equal(3, counts.Total)
2407 })
2408 }
2409
2410 func TestCommand_HelpFlagTakesPrecedenceOverParseErrors(t *testing.T) {
2411 t.Run("root command with --help and bad flag", func(t *testing.T) {
2412 r := require.New(t)
2413 var buf bytes.Buffer
2414 var errBuf bytes.Buffer
2415
2416 cmd := &Command{
2417 Writer: &buf,
2418 ErrWriter: &errBuf,
2419 Action: func(ctx context.Context, cmd *Command) error {
2420 return nil
2421 },
2422 }
2423
2424 err := cmd.Run(buildTestContext(t), []string{"command", "--help", "--undefined"})
2425 r.NoError(err)
2426 r.Contains(buf.String(), "NAME:")
2427 r.Contains(buf.String(), "command")
2428 r.NotContains(errBuf.String(), "Incorrect Usage")
2429 })
2430
2431 t.Run("root command with -h and bad flag", func(t *testing.T) {
2432 r := require.New(t)
2433 var buf bytes.Buffer
2434 var errBuf bytes.Buffer
2435
2436 cmd := &Command{
2437 Writer: &buf,
2438 ErrWriter: &errBuf,
2439 Action: func(ctx context.Context, cmd *Command) error {
2440 return nil
2441 },
2442 }
2443
2444 err := cmd.Run(buildTestContext(t), []string{"command", "-h", "--undefined"})
2445 r.NoError(err)
2446 r.Contains(buf.String(), "NAME:")
2447 r.Contains(buf.String(), "command")
2448 r.NotContains(errBuf.String(), "Incorrect Usage")
2449 })
2450
2451 t.Run("subcommand with --help and bad flag", func(t *testing.T) {
2452 r := require.New(t)
2453 var buf bytes.Buffer
2454 var errBuf bytes.Buffer
2455
2456 cmd := &Command{
2457 Writer: &buf,
2458 ErrWriter: &errBuf,
2459 Action: func(ctx context.Context, cmd *Command) error {
2460 return nil
2461 },
2462 Commands: []*Command{
2463 {
2464 Name: "foo",
2465 Action: func(ctx context.Context, cmd *Command) error {
2466 return nil
2467 },
2468 },
2469 },
2470 }
2471
2472 err := cmd.Run(buildTestContext(t), []string{"command", "foo", "--help", "--undefined"})
2473 r.NoError(err)
2474 r.Contains(buf.String(), "NAME:")
2475 r.Contains(buf.String(), "foo")
2476 r.NotContains(errBuf.String(), "Incorrect Usage")
2477 })
2478
2479 t.Run("subcommand with bad flag shows Incorrect Usage and help", func(t *testing.T) {
2480 r := require.New(t)
2481 var buf bytes.Buffer
2482 var errBuf bytes.Buffer
2483
2484 cmd := &Command{
2485 Writer: &buf,
2486 ErrWriter: &errBuf,
2487 Action: func(ctx context.Context, cmd *Command) error {
2488 return nil
2489 },
2490 Commands: []*Command{
2491 {
2492 Name: "foo",
2493 Action: func(ctx context.Context, cmd *Command) error {
2494 return nil
2495 },
2496 },
2497 },
2498 }
2499
2500 err := cmd.Run(buildTestContext(t), []string{"command", "foo", "--undefined"})
2501 r.Error(err)
2502 r.Contains(buf.String(), "NAME:")
2503 r.Contains(buf.String(), "foo")
2504 r.Contains(errBuf.String(), "Incorrect Usage")
2505 })
2506 }
2507
2508 func TestFlagActionOrder(t *testing.T) {
2509 tests := []struct {
2510 Name string
2511 Args []string
2512 }{
2513 {
2514 Name: "abc",
2515 Args: []string{"", "--a", "--b", "--c"},
2516 },
2517 {
2518 Name: "bca",
2519 Args: []string{"", "--b", "--c", "--a"},
2520 },
2521 {
2522 Name: "cba",
2523 Args: []string{"", "--c", "--b", "--a"},
2524 },
2525 }
2526 for _, tt := range tests {
2527 t.Run(tt.Name, func(t *testing.T) {
2528 str := ""
2529 action := func(name string) func(context.Context, *Command, bool) error {
2530 return func(_ context.Context, _ *Command, _ bool) error {
2531 str += name
2532 return nil
2533 }
2534 }
2535 cmd := &Command{
2536 Flags: []Flag{
2537 &BoolFlag{Name: "a", Action: action("a")},
2538 &BoolFlag{Name: "b", Action: action("b")},
2539 &BoolFlag{Name: "c", Action: action("c")},
2540 },
2541 Action: func(_ context.Context, cmd *Command) error {
2542 return nil
2543 },
2544 }
2545
2546 err := cmd.Run(buildTestContext(t), tt.Args)
2547 require.NoError(t, err)
2548
2549 if str != "abc" {
2550 t.Errorf("expected 'abc' got '%s'", str)
2551 }
2552 })
2553 }
2554 }
2555
2556 func TestCommand_Run_CommandWithSubcommandHasHelpTopic(t *testing.T) {
2557 subcommandHelpTopics := [][]string{
2558 {"foo", "--help"},
2559 {"foo", "-h"},
2560 {"foo", "help"},
2561 }
2562
2563 for _, flagSet := range subcommandHelpTopics {
2564 t.Run(fmt.Sprintf("checking with flags %v", flagSet), func(t *testing.T) {
2565 buf := new(bytes.Buffer)
2566
2567 subCmdBar := &Command{
2568 Name: "bar",
2569 Usage: "does bar things",
2570 }
2571 subCmdBaz := &Command{
2572 Name: "baz",
2573 Usage: "does baz things",
2574 }
2575 cmd := &Command{
2576 Name: "foo",
2577 Description: "descriptive wall of text about how it does foo things",
2578 Commands: []*Command{subCmdBar, subCmdBaz},
2579 Action: func(context.Context, *Command) error { return nil },
2580 Writer: buf,
2581 }
2582
2583 err := cmd.Run(buildTestContext(t), flagSet)
2584 assert.NoError(t, err)
2585
2586 output := buf.String()
2587
2588 assert.NotContains(t, output, "No help topic for", "expect a help topic, got none")
2589
2590 for _, shouldContain := range []string{
2591 cmd.Name, cmd.Description,
2592 subCmdBar.Name, subCmdBar.Usage,
2593 subCmdBaz.Name, subCmdBaz.Usage,
2594 } {
2595 assert.Contains(t, output, shouldContain, "want help to contain %q, did not: \n%q", shouldContain, output)
2596 }
2597 })
2598 }
2599 }
2600
2601 func TestCommand_Run_SubcommandFullPath(t *testing.T) {
2602 out := &bytes.Buffer{}
2603
2604 subCmd := &Command{
2605 Name: "bar",
2606 Usage: "does bar things",
2607 ArgsUsage: "[arguments...]",
2608 }
2609
2610 cmd := &Command{
2611 Name: "foo",
2612 Description: "foo commands",
2613 Commands: []*Command{subCmd},
2614 Writer: out,
2615 }
2616
2617 require.NoError(t, cmd.Run(buildTestContext(t), []string{"foo", "bar", "--help"}))
2618
2619 outString := out.String()
2620 require.Contains(t, outString, "foo bar - does bar things")
2621 require.Contains(t, outString, "foo bar [options] [arguments...]")
2622 }
2623
2624 func TestCommand_Run_Help(t *testing.T) {
2625 tests := []struct {
2626 helpArguments []string
2627 hideHelp bool
2628 wantContains string
2629 wantErr error
2630 }{
2631 {
2632 helpArguments: []string{"boom", "--help"},
2633 hideHelp: false,
2634 wantContains: "boom - make an explosive entrance",
2635 },
2636 {
2637 helpArguments: []string{"boom", "-h"},
2638 hideHelp: false,
2639 wantContains: "boom - make an explosive entrance",
2640 },
2641 {
2642 helpArguments: []string{"boom", "help"},
2643 hideHelp: false,
2644 wantContains: "boom - make an explosive entrance",
2645 },
2646 {
2647 helpArguments: []string{"boom", "--help"},
2648 hideHelp: true,
2649 wantErr: fmt.Errorf("flag provided but not defined: -help"),
2650 },
2651 {
2652 helpArguments: []string{"boom", "-h"},
2653 hideHelp: true,
2654 wantErr: fmt.Errorf("flag provided but not defined: -h"),
2655 },
2656 {
2657 helpArguments: []string{"boom", "help"},
2658 hideHelp: true,
2659 wantContains: "boom I say!",
2660 },
2661 }
2662
2663 for _, tt := range tests {
2664 t.Run(fmt.Sprintf("checking with arguments %v%v", tt.helpArguments, tt.hideHelp), func(t *testing.T) {
2665 buf := new(bytes.Buffer)
2666
2667 cmd := &Command{
2668 Name: "boom",
2669 Usage: "make an explosive entrance",
2670 Writer: buf,
2671 HideHelp: tt.hideHelp,
2672 Action: func(context.Context, *Command) error {
2673 buf.WriteString("boom I say!")
2674 return nil
2675 },
2676 }
2677
2678 err := cmd.Run(buildTestContext(t), tt.helpArguments)
2679 if tt.wantErr != nil {
2680 assert.ErrorContains(t, err, tt.wantErr.Error())
2681 }
2682
2683 output := buf.String()
2684
2685 assert.Contains(t, output, tt.wantContains, "want help to contain %q, did not: \n%q", "boom - make an explosive entrance", output)
2686 })
2687 }
2688 }
2689
2690 func TestCommand_Run_Version(t *testing.T) {
2691 versionArguments := [][]string{{"boom", "--version"}, {"boom", "-v"}}
2692
2693 for _, args := range versionArguments {
2694 t.Run(fmt.Sprintf("checking with arguments %v", args), func(t *testing.T) {
2695 buf := new(bytes.Buffer)
2696
2697 cmd := &Command{
2698 Name: "boom",
2699 Usage: "make an explosive entrance",
2700 Version: "0.1.0",
2701 Writer: buf,
2702 Action: func(context.Context, *Command) error {
2703 buf.WriteString("boom I say!")
2704 return nil
2705 },
2706 }
2707
2708 err := cmd.Run(buildTestContext(t), args)
2709 assert.NoError(t, err)
2710 assert.Contains(t, buf.String(), "0.1.0", "want version to contain 0.1.0")
2711 })
2712 }
2713 }
2714
2715 func TestCommand_Run_CustomFlagCanUseVersionAlias(t *testing.T) {
2716 buf := new(bytes.Buffer)
2717 called := false
2718
2719 cmd := &Command{
2720 Name: "boom",
2721 Version: "0.1.0",
2722 Writer: buf,
2723 Flags: []Flag{
2724 &BoolFlag{Name: "verbose", Aliases: []string{"v"}},
2725 },
2726 Action: func(_ context.Context, cmd *Command) error {
2727 called = true
2728 assert.True(t, cmd.Bool("verbose"))
2729 return nil
2730 },
2731 }
2732
2733 err := cmd.Run(buildTestContext(t), []string{"boom", "-v"})
2734
2735 assert.NoError(t, err)
2736 assert.True(t, called)
2737 assert.Empty(t, buf.String())
2738 }
2739
2740 func TestCommand_Run_Categories(t *testing.T) {
2741 buf := new(bytes.Buffer)
2742
2743 cmd := &Command{
2744 Name: "categories",
2745 HideHelp: true,
2746 Commands: []*Command{
2747 {
2748 Name: "command1",
2749 Category: "1",
2750 },
2751 {
2752 Name: "command2",
2753 Category: "1",
2754 },
2755 {
2756 Name: "command3",
2757 Category: "2",
2758 },
2759 },
2760 Writer: buf,
2761 }
2762
2763 _ = cmd.Run(buildTestContext(t), []string{"categories"})
2764
2765 expect := commandCategories([]*commandCategory{
2766 {
2767 name: "1",
2768 commands: []*Command{
2769 cmd.Commands[0],
2770 cmd.Commands[1],
2771 },
2772 },
2773 {
2774 name: "2",
2775 commands: []*Command{
2776 cmd.Commands[2],
2777 },
2778 },
2779 })
2780
2781 require.Equal(t, &expect, cmd.categories)
2782
2783 output := buf.String()
2784
2785 assert.Contains(t, output, "1:\n command1", "want buffer to include category %q, did not: \n%q", "1:\n command1", output)
2786 }
2787
2788 func TestCommand_VisibleCategories(t *testing.T) {
2789 cmd := &Command{
2790 Name: "visible-categories",
2791 HideHelp: true,
2792 Commands: []*Command{
2793 {
2794 Name: "command1",
2795 Category: "1",
2796 Hidden: true,
2797 },
2798 {
2799 Name: "command2",
2800 Category: "2",
2801 },
2802 {
2803 Name: "command3",
2804 Category: "3",
2805 },
2806 },
2807 }
2808
2809 expected := []CommandCategory{
2810 &commandCategory{
2811 name: "2",
2812 commands: []*Command{
2813 cmd.Commands[1],
2814 },
2815 },
2816 &commandCategory{
2817 name: "3",
2818 commands: []*Command{
2819 cmd.Commands[2],
2820 },
2821 },
2822 }
2823
2824 cmd.setupDefaults([]string{"test"})
2825 assert.Equal(t, expected, cmd.VisibleCategories())
2826
2827 cmd = &Command{
2828 Name: "visible-categories",
2829 HideHelp: true,
2830 Commands: []*Command{
2831 {
2832 Name: "command1",
2833 Category: "1",
2834 Hidden: true,
2835 },
2836 {
2837 Name: "command2",
2838 Category: "2",
2839 Hidden: true,
2840 },
2841 {
2842 Name: "command3",
2843 Category: "3",
2844 },
2845 },
2846 }
2847
2848 expected = []CommandCategory{
2849 &commandCategory{
2850 name: "3",
2851 commands: []*Command{
2852 cmd.Commands[2],
2853 },
2854 },
2855 }
2856
2857 cmd.setupDefaults([]string{"test"})
2858 assert.Equal(t, expected, cmd.VisibleCategories())
2859
2860 cmd = &Command{
2861 Name: "visible-categories",
2862 HideHelp: true,
2863 Commands: []*Command{
2864 {
2865 Name: "command1",
2866 Category: "1",
2867 Hidden: true,
2868 },
2869 {
2870 Name: "command2",
2871 Category: "2",
2872 Hidden: true,
2873 },
2874 {
2875 Name: "command3",
2876 Category: "3",
2877 Hidden: true,
2878 },
2879 },
2880 }
2881
2882 cmd.setupDefaults([]string{"test"})
2883 assert.Empty(t, cmd.VisibleCategories())
2884 }
2885
2886 func TestCommand_Run_SubcommandDoesNotOverwriteErrorFromBefore(t *testing.T) {
2887 cmd := &Command{
2888 Commands: []*Command{
2889 {
2890 Commands: []*Command{
2891 {
2892 Name: "sub",
2893 },
2894 },
2895 Name: "bar",
2896 Before: func(context.Context, *Command) (context.Context, error) { return nil, fmt.Errorf("before error") },
2897 After: func(context.Context, *Command) error { return fmt.Errorf("after error") },
2898 },
2899 },
2900 }
2901
2902 err := cmd.Run(buildTestContext(t), []string{"foo", "bar"})
2903 assert.ErrorContains(t, err, "before error")
2904 assert.ErrorContains(t, err, "after error")
2905 }
2906
2907 func TestCommand_OnUsageError_WithWrongFlagValue_ForSubcommand(t *testing.T) {
2908 cmd := &Command{
2909 Flags: []Flag{
2910 &Int64Flag{Name: "flag"},
2911 },
2912 OnUsageError: func(_ context.Context, _ *Command, err error, isSubcommand bool) error {
2913 assert.False(t, isSubcommand, "Expect subcommand")
2914 assert.ErrorContains(t, err, "\"wrong\": invalid syntax")
2915 return errors.New("intercepted: " + err.Error())
2916 },
2917 Commands: []*Command{
2918 {
2919 Name: "bar",
2920 },
2921 },
2922 }
2923
2924 err := cmd.Run(buildTestContext(t), []string{"foo", "--flag=wrong", "bar"})
2925 assert.ErrorContains(t, err, "parsing \"wrong\": invalid syntax", "Expect an intercepted error")
2926 }
2927
2928 // A custom flag that conforms to the relevant interfaces, but has none of the
2929 // fields that the other flag types do.
2930 type customBoolFlag struct {
2931 Nombre string
2932 }
2933
2934 // Don't use the normal FlagStringer
2935 func (c *customBoolFlag) String() string {
2936 return "***" + c.Nombre + "***"
2937 }
2938
2939 func (c *customBoolFlag) Names() []string {
2940 return []string{c.Nombre}
2941 }
2942
2943 func (c *customBoolFlag) TakesValue() bool {
2944 return false
2945 }
2946
2947 func (c *customBoolFlag) GetValue() string {
2948 return "value"
2949 }
2950
2951 func (c *customBoolFlag) GetUsage() string {
2952 return "usage"
2953 }
2954
2955 func (c *customBoolFlag) PreParse() error {
2956 return nil
2957 }
2958
2959 func (c *customBoolFlag) PostParse() error {
2960 return nil
2961 }
2962
2963 func (c *customBoolFlag) Get() any {
2964 dest := false
2965 return &boolValue{
2966 destination: &dest,
2967 }
2968 }
2969
2970 func (c *customBoolFlag) Set(_, _ string) error {
2971 return nil
2972 }
2973
2974 func (c *customBoolFlag) RunAction(context.Context, *Command) error {
2975 return nil
2976 }
2977
2978 func (c *customBoolFlag) IsSet() bool {
2979 return false
2980 }
2981
2982 func (c *customBoolFlag) IsRequired() bool {
2983 return false
2984 }
2985
2986 func (c *customBoolFlag) IsVisible() bool {
2987 return false
2988 }
2989
2990 func (c *customBoolFlag) GetCategory() string {
2991 return ""
2992 }
2993
2994 func (c *customBoolFlag) GetEnvVars() []string {
2995 return nil
2996 }
2997
2998 func (c *customBoolFlag) GetDefaultText() string {
2999 return ""
3000 }
3001
3002 func TestCustomFlagsUnused(t *testing.T) {
3003 cmd := &Command{
3004 Flags: []Flag{&customBoolFlag{"custom"}},
3005 Writer: io.Discard,
3006 }
3007
3008 err := cmd.Run(buildTestContext(t), []string{"foo"})
3009 assert.NoError(t, err, "Run returned unexpected error")
3010 }
3011
3012 func TestCustomFlagsUsed(t *testing.T) {
3013 cmd := &Command{
3014 Flags: []Flag{&customBoolFlag{"custom"}},
3015 Writer: io.Discard,
3016 }
3017
3018 err := cmd.Run(buildTestContext(t), []string{"foo", "--custom=bar"})
3019 assert.NoError(t, err, "Run returned unexpected error")
3020 }
3021
3022 // Regression for #2229. When a user flag claims the -v alias, only that
3023 // alias is yielded: --version must still print the version.
3024 func TestVersionFlagWorksWhenAliasYieldedToUserFlag(t *testing.T) {
3025 buf := new(bytes.Buffer)
3026 called := false
3027
3028 cmd := &Command{
3029 Name: "boom",
3030 Version: "0.1.0",
3031 Writer: buf,
3032 Flags: []Flag{
3033 &BoolFlag{Name: "verbose", Aliases: []string{"v"}},
3034 },
3035 Action: func(_ context.Context, _ *Command) error {
3036 called = true
3037 return nil
3038 },
3039 }
3040
3041 err := cmd.Run(buildTestContext(t), []string{"boom", "--version"})
3042
3043 assert.NoError(t, err)
3044 assert.False(t, called, "version should short-circuit the action")
3045 assert.Contains(t, buf.String(), "0.1.0")
3046 }
3047
3048 func TestDropClashingAliases(t *testing.T) {
3049 verbose := &BoolFlag{Name: "verbose", Aliases: []string{"v"}}
3050
3051 for _, tc := range []struct {
3052 name string
3053 aliases []string
3054 flags []Flag
3055 selfName string
3056 want []string
3057 }{
3058 {name: "no aliases", aliases: nil, flags: []Flag{verbose}, selfName: "version", want: nil},
3059 {name: "no flags", aliases: []string{"v"}, flags: nil, selfName: "version", want: []string{"v"}},
3060 {name: "drops clashing alias", aliases: []string{"v"}, flags: []Flag{verbose}, selfName: "version", want: []string{}},
3061 {name: "keeps free alias", aliases: []string{"V"}, flags: []Flag{verbose}, selfName: "version", want: []string{"V"}},
3062 {name: "keeps selfName even if claimed", aliases: []string{"verbose"}, flags: []Flag{verbose}, selfName: "verbose", want: []string{"verbose"}},
3063 } {
3064 t.Run(tc.name, func(t *testing.T) {
3065 assert.Equal(t, tc.want, dropClashingAliases(tc.aliases, tc.flags, tc.selfName))
3066 })
3067 }
3068 }
3069
3070 func TestCustomHelpVersionFlags(t *testing.T) {
3071 cmd := &Command{
3072 Writer: io.Discard,
3073 }
3074
3075 // Be sure to reset the global flags
3076 defer func(helpFlag Flag, versionFlag Flag) {
3077 HelpFlag = helpFlag.(*BoolFlag)
3078 VersionFlag = versionFlag.(*BoolFlag)
3079 }(HelpFlag, VersionFlag)
3080
3081 HelpFlag = &customBoolFlag{"help-custom"}
3082 VersionFlag = &customBoolFlag{"version-custom"}
3083
3084 err := cmd.Run(buildTestContext(t), []string{"foo", "--help-custom=bar"})
3085 assert.NoError(t, err, "Run returned unexpected error")
3086 }
3087
3088 func TestHandleExitCoder_Default(t *testing.T) {
3089 app := buildMinimalTestCommand()
3090 _ = app.handleExitCoder(context.Background(), Exit("Default Behavior Error", 42))
3091
3092 output := fakeErrWriter.String()
3093 assert.Contains(t, output, "Default", "Expected Default Behavior from Error Handler")
3094 }
3095
3096 func TestHandleExitCoder_Custom(t *testing.T) {
3097 cmd := buildMinimalTestCommand()
3098
3099 cmd.ExitErrHandler = func(context.Context, *Command, error) {
3100 _, _ = fmt.Fprintln(ErrWriter, "I'm a Custom error handler, I print what I want!")
3101 }
3102
3103 _ = cmd.handleExitCoder(context.Background(), Exit("Default Behavior Error", 42))
3104
3105 output := fakeErrWriter.String()
3106 assert.Contains(t, output, "Custom", "Expected Custom Behavior from Error Handler")
3107 }
3108
3109 func TestShellCompletionForIncompleteFlags(t *testing.T) {
3110 cmd := &Command{
3111 Flags: []Flag{
3112 &Int64Flag{
3113 Name: "test-completion",
3114 },
3115 },
3116 EnableShellCompletion: true,
3117 ShellComplete: func(_ context.Context, cmd *Command) {
3118 for _, command := range cmd.Commands {
3119 if command.Hidden {
3120 continue
3121 }
3122
3123 for _, name := range command.Names() {
3124 _, _ = fmt.Fprintln(cmd.Writer, name)
3125 }
3126 }
3127
3128 for _, fl := range cmd.Flags {
3129 for _, name := range fl.Names() {
3130 if name == GenerateShellCompletionFlag.Names()[0] {
3131 continue
3132 }
3133
3134 switch name = strings.TrimSpace(name); len(name) {
3135 case 0:
3136 case 1:
3137 _, _ = fmt.Fprintln(cmd.Writer, "-"+name)
3138 default:
3139 _, _ = fmt.Fprintln(cmd.Writer, "--"+name)
3140 }
3141 }
3142 }
3143 },
3144 Action: func(context.Context, *Command) error {
3145 return fmt.Errorf("should not get here")
3146 },
3147 Writer: io.Discard,
3148 }
3149
3150 err := cmd.Run(buildTestContext(t), []string{"", "--test-completion", completionFlag})
3151 assert.NoError(t, err, "app should not return an error")
3152 }
3153
3154 func TestWhenExitSubCommandWithCodeThenCommandQuitUnexpectedly(t *testing.T) {
3155 testCode := 104
3156
3157 cmd := buildMinimalTestCommand()
3158 cmd.Commands = []*Command{
3159 {
3160 Name: "cmd",
3161 Commands: []*Command{
3162 {
3163 Name: "subcmd",
3164 Action: func(context.Context, *Command) error {
3165 return Exit("exit error", testCode)
3166 },
3167 },
3168 },
3169 },
3170 }
3171
3172 // set user function as ExitErrHandler
3173 exitCodeFromExitErrHandler := int(0)
3174 cmd.ExitErrHandler = func(_ context.Context, _ *Command, err error) {
3175 if exitErr, ok := err.(ExitCoder); ok {
3176 exitCodeFromExitErrHandler = exitErr.ExitCode()
3177 }
3178 }
3179
3180 // keep and restore original OsExiter
3181 origExiter := OsExiter
3182 t.Cleanup(func() { OsExiter = origExiter })
3183
3184 // set user function as OsExiter
3185 exitCodeFromOsExiter := int(0)
3186 OsExiter = func(exitCode int) {
3187 exitCodeFromOsExiter = exitCode
3188 }
3189
3190 r := require.New(t)
3191
3192 r.Error(cmd.Run(buildTestContext(t), []string{
3193 "myapp",
3194 "cmd",
3195 "subcmd",
3196 }))
3197
3198 r.Equal(0, exitCodeFromOsExiter)
3199 r.Equal(testCode, exitCodeFromExitErrHandler)
3200 }
3201
3202 func buildMinimalTestCommand() *Command {
3203 // reset the help flag because tests may have set it
3204 HelpFlag.(*BoolFlag).hasBeenSet = false
3205 return &Command{Writer: io.Discard}
3206 }
3207
3208 func TestSetupInitializesBothWriters(t *testing.T) {
3209 cmd := &Command{}
3210
3211 cmd.setupDefaults([]string{"test"})
3212
3213 assert.Equal(t, cmd.ErrWriter, os.Stderr, "expected a.ErrWriter to be os.Stderr")
3214 assert.Equal(t, cmd.Writer, os.Stdout, "expected a.Writer to be os.Stdout")
3215 }
3216
3217 func TestSetupInitializesOnlyNilWriters(t *testing.T) {
3218 wr := &bytes.Buffer{}
3219 cmd := &Command{
3220 ErrWriter: wr,
3221 }
3222
3223 cmd.setupDefaults([]string{"test"})
3224
3225 assert.Equal(t, cmd.ErrWriter, wr, "expected a.ErrWriter to be a *bytes.Buffer instance")
3226 assert.Equal(t, cmd.Writer, os.Stdout, "expected a.Writer to be os.Stdout")
3227 }
3228
3229 // Regression for #2325. A Writer set on the root command should reach
3230 // the subcommand's Action via c.Writer, not get silently replaced by
3231 // os.Stdout the first time the subcommand runs setupDefaults.
3232 func TestSubcommandInheritsRootWriters(t *testing.T) {
3233 var out, errOut bytes.Buffer
3234 root := &Command{
3235 Name: "demo",
3236 Writer: &out,
3237 ErrWriter: &errOut,
3238 Commands: []*Command{
3239 {
3240 Name: "sub",
3241 Action: func(_ context.Context, c *Command) error {
3242 _, _ = fmt.Fprintln(c.Writer, "from sub")
3243 _, _ = fmt.Fprintln(c.ErrWriter, "errors from sub")
3244 return nil
3245 },
3246 },
3247 },
3248 }
3249
3250 assert.NoError(t, root.Run(buildTestContext(t), []string{"demo", "sub"}))
3251 assert.Equal(t, "from sub\n", out.String())
3252 assert.Equal(t, "errors from sub\n", errOut.String())
3253 }
3254
3255 func TestFlagAction(t *testing.T) {
3256 now := time.Now().UTC().Truncate(time.Minute)
3257 testCases := []struct {
3258 name string
3259 args []string
3260 err string
3261 exp string
3262 }{
3263 {
3264 name: "flag_string",
3265 args: []string{"app", "--f_string=string"},
3266 exp: "string ",
3267 },
3268 {
3269 name: "flag_string_error",
3270 args: []string{"app", "--f_string="},
3271 err: "empty string",
3272 },
3273 {
3274 name: "flag_string_error2",
3275 args: []string{"app", "--f_string=", "--f_bool"},
3276 err: "empty string",
3277 },
3278 {
3279 name: "flag_string_slice",
3280 args: []string{"app", "--f_string_slice=s1,s2,s3"},
3281 exp: "[s1 s2 s3] ",
3282 },
3283 {
3284 name: "flag_string_slice_error",
3285 args: []string{"app", "--f_string_slice=err"},
3286 err: "error string slice",
3287 },
3288 {
3289 name: "flag_bool",
3290 args: []string{"app", "--f_bool"},
3291 exp: "true ",
3292 },
3293 {
3294 name: "flag_bool_error",
3295 args: []string{"app", "--f_bool=false"},
3296 err: "value is false",
3297 },
3298 {
3299 name: "flag_duration",
3300 args: []string{"app", "--f_duration=1h30m20s"},
3301 exp: "1h30m20s ",
3302 },
3303 {
3304 name: "flag_duration_error",
3305 args: []string{"app", "--f_duration=0"},
3306 err: "empty duration",
3307 },
3308 {
3309 name: "flag_float64",
3310 args: []string{"app", "--f_float64=3.14159"},
3311 exp: "3.14159 ",
3312 },
3313 {
3314 name: "flag_float64_error",
3315 args: []string{"app", "--f_float64=-1"},
3316 err: "negative float64",
3317 },
3318 {
3319 name: "flag_float64_slice",
3320 args: []string{"app", "--f_float64_slice=1.1,2.2,3.3"},
3321 exp: "[1.1 2.2 3.3] ",
3322 },
3323 {
3324 name: "flag_float64_slice_error",
3325 args: []string{"app", "--f_float64_slice=-1"},
3326 err: "invalid float64 slice",
3327 },
3328 {
3329 name: "flag_int",
3330 args: []string{"app", "--f_int=1"},
3331 exp: "1 ",
3332 },
3333 {
3334 name: "flag_int_error",
3335 args: []string{"app", "--f_int=-1"},
3336 err: "negative int",
3337 },
3338 {
3339 name: "flag_int_slice",
3340 args: []string{"app", "--f_int_slice=1,2,3"},
3341 exp: "[1 2 3] ",
3342 },
3343 {
3344 name: "flag_int_slice_error",
3345 args: []string{"app", "--f_int_slice=-1"},
3346 err: "invalid int slice",
3347 },
3348 {
3349 name: "flag_timestamp",
3350 args: []string{"app", "--f_timestamp", now.Format(time.DateTime)},
3351 exp: now.UTC().Format(time.RFC3339) + " ",
3352 },
3353 {
3354 name: "flag_timestamp_error",
3355 args: []string{"app", "--f_timestamp", "0001-01-01 00:00:00"},
3356 err: "zero timestamp",
3357 },
3358 {
3359 name: "flag_uint",
3360 args: []string{"app", "--f_uint=1"},
3361 exp: "1 ",
3362 },
3363 {
3364 name: "flag_uint_error",
3365 args: []string{"app", "--f_uint=0"},
3366 err: "zero uint64",
3367 },
3368 {
3369 name: "flag_no_action",
3370 args: []string{"app", "--f_no_action=xx"},
3371 exp: "",
3372 },
3373 {
3374 name: "command_flag",
3375 args: []string{"app", "c1", "--f_string=c1"},
3376 exp: "c1 ",
3377 },
3378 {
3379 name: "subCommand_flag",
3380 args: []string{"app", "c1", "sub1", "--f_string=sub1"},
3381 exp: "sub1 ",
3382 },
3383 // TBD
3384 /* {
3385 name: "mixture",
3386 args: []string{"app", "--f_string=app", "--f_uint=1", "--f_int_slice=1,2,3", "--f_duration=1h30m20s", "c1", "--f_string=c1", "sub1", "--f_string=sub1"},
3387 exp: "app 1 [1 2 3] 1h30m20s c1 sub1 ",
3388 },*/
3389 {
3390 name: "flag_string_map",
3391 args: []string{"app", "--f_string_map=s1=s2,s3="},
3392 exp: "map[s1:s2 s3:]",
3393 },
3394 {
3395 name: "flag_string_map_error",
3396 args: []string{"app", "--f_string_map=err="},
3397 err: "error string map",
3398 },
3399 }
3400
3401 for _, test := range testCases {
3402 t.Run(test.name, func(t *testing.T) {
3403 out := &bytes.Buffer{}
3404
3405 newStringFlag := func(local bool) *StringFlag {
3406 return &StringFlag{
3407 Local: local,
3408 Name: "f_string",
3409 Action: func(_ context.Context, cmd *Command, v string) error {
3410 if v == "" {
3411 return fmt.Errorf("empty string")
3412 }
3413 _, err := cmd.Root().Writer.Write([]byte(v + " "))
3414 return err
3415 },
3416 }
3417 }
3418
3419 cmd := &Command{
3420 Writer: out,
3421 Name: "app",
3422 Commands: []*Command{
3423 {
3424 Name: "c1",
3425 Flags: []Flag{newStringFlag(true)},
3426 Action: func(_ context.Context, cmd *Command) error { return nil },
3427 Commands: []*Command{
3428 {
3429 Name: "sub1",
3430 Action: func(context.Context, *Command) error { return nil },
3431 Flags: []Flag{newStringFlag(true)},
3432 },
3433 },
3434 },
3435 },
3436 Flags: []Flag{
3437 newStringFlag(true),
3438 &StringFlag{
3439 Name: "f_no_action",
3440 },
3441 &StringSliceFlag{
3442 Local: true,
3443 Name: "f_string_slice",
3444 Action: func(_ context.Context, cmd *Command, v []string) error {
3445 if v[0] == "err" {
3446 return fmt.Errorf("error string slice")
3447 }
3448 _, err := fmt.Fprintf(cmd.Root().Writer, "%v ", v)
3449 return err
3450 },
3451 },
3452 &BoolFlag{
3453 Name: "f_bool",
3454 Local: true,
3455 Action: func(_ context.Context, cmd *Command, v bool) error {
3456 if !v {
3457 return fmt.Errorf("value is false")
3458 }
3459 _, err := fmt.Fprintf(cmd.Root().Writer, "%t ", v)
3460 return err
3461 },
3462 },
3463 &DurationFlag{
3464 Name: "f_duration",
3465 Local: true,
3466 Action: func(_ context.Context, cmd *Command, v time.Duration) error {
3467 if v == 0 {
3468 return fmt.Errorf("empty duration")
3469 }
3470 _, err := fmt.Fprintf(cmd.Root().Writer, v.String()+" ")
3471 return err
3472 },
3473 },
3474 &FloatFlag{
3475 Name: "f_float64",
3476 Local: true,
3477 Action: func(_ context.Context, cmd *Command, v float64) error {
3478 if v < 0 {
3479 return fmt.Errorf("negative float64")
3480 }
3481 _, err := fmt.Fprintf(cmd.Root().Writer, strconv.FormatFloat(v, 'f', -1, 64)+" ")
3482 return err
3483 },
3484 },
3485 &FloatSliceFlag{
3486 Name: "f_float64_slice",
3487 Local: true,
3488 Action: func(_ context.Context, cmd *Command, v []float64) error {
3489 if len(v) > 0 && v[0] < 0 {
3490 return fmt.Errorf("invalid float64 slice")
3491 }
3492 _, err := fmt.Fprintf(cmd.Root().Writer, "%v ", v)
3493 return err
3494 },
3495 },
3496 &Int64Flag{
3497 Name: "f_int",
3498 Local: true,
3499 Action: func(_ context.Context, cmd *Command, v int64) error {
3500 if v < 0 {
3501 return fmt.Errorf("negative int")
3502 }
3503 _, err := fmt.Fprintf(cmd.Root().Writer, "%v ", v)
3504 return err
3505 },
3506 },
3507 &Int64SliceFlag{
3508 Name: "f_int_slice",
3509 Local: true,
3510 Action: func(_ context.Context, cmd *Command, v []int64) error {
3511 if len(v) > 0 && v[0] < 0 {
3512 return fmt.Errorf("invalid int slice")
3513 }
3514 _, err := fmt.Fprintf(cmd.Root().Writer, "%v ", v)
3515 return err
3516 },
3517 },
3518 &TimestampFlag{
3519 Name: "f_timestamp",
3520 Local: true,
3521 Config: TimestampConfig{
3522 Timezone: time.UTC,
3523 Layouts: []string{time.DateTime},
3524 },
3525 Action: func(_ context.Context, cmd *Command, v time.Time) error {
3526 if v.IsZero() {
3527 return fmt.Errorf("zero timestamp")
3528 }
3529
3530 _, err := cmd.Root().Writer.Write([]byte(v.Format(time.RFC3339) + " "))
3531 return err
3532 },
3533 },
3534 &Uint64Flag{
3535 Name: "f_uint",
3536 Local: true,
3537 Action: func(_ context.Context, cmd *Command, v uint64) error {
3538 if v == 0 {
3539 return fmt.Errorf("zero uint64")
3540 }
3541 _, err := fmt.Fprintf(cmd.Root().Writer, "%v ", v)
3542 return err
3543 },
3544 },
3545 &StringMapFlag{
3546 Name: "f_string_map",
3547 Local: true,
3548 Action: func(_ context.Context, cmd *Command, v map[string]string) error {
3549 if _, ok := v["err"]; ok {
3550 return fmt.Errorf("error string map")
3551 }
3552 _, err := fmt.Fprintf(cmd.Root().Writer, "%v", v)
3553 return err
3554 },
3555 },
3556 },
3557 Action: func(context.Context, *Command) error { return nil },
3558 }
3559
3560 err := cmd.Run(buildTestContext(t), test.args)
3561
3562 r := require.New(t)
3563
3564 if test.err != "" {
3565 r.EqualError(err, test.err)
3566 return
3567 }
3568
3569 r.NoError(err)
3570 r.Equal(test.exp, out.String())
3571 })
3572 }
3573 }
3574
3575 func TestLocalSliceFlagAccumulation(t *testing.T) {
3576 var got []string
3577
3578 app := &Command{
3579 Name: "app",
3580 Commands: []*Command{
3581 {
3582 Name: "sub",
3583 Flags: []Flag{
3584 &StringSliceFlag{
3585 Name: "paths",
3586 Aliases: []string{"p"},
3587 Local: true,
3588 Destination: &got,
3589 },
3590 },
3591 Action: func(_ context.Context, cmd *Command) error {
3592 return nil
3593 },
3594 },
3595 },
3596 }
3597
3598 err := app.Run(context.Background(), []string{"app", "sub", "-p", "/a", "-p", "/b", "-p", "/c"})
3599 if err != nil {
3600 t.Fatal(err)
3601 }
3602
3603 if len(got) != 3 {
3604 t.Errorf("expected 3 values, got %d: %v", len(got), got)
3605 }
3606 }
3607
3608 func TestLocalFlagError(t *testing.T) {
3609 var topInt int64
3610
3611 cmd := &Command{
3612 Flags: []Flag{
3613 &Int64Flag{
3614 Name: "cmdFlag",
3615 Destination: &topInt,
3616 Local: true,
3617 },
3618 },
3619 Commands: []*Command{
3620 {
3621 Name: "subcmd",
3622 },
3623 },
3624 }
3625
3626 err := cmd.Run(buildTestContext(t), []string{
3627 "app",
3628 "subcmd",
3629 "--cmdFlag", "11",
3630 })
3631
3632 assert.Error(t, err)
3633 assert.Contains(t, err.Error(), "flag provided but not defined: -cmdFlag")
3634 }
3635
3636 func TestPersistentFlag(t *testing.T) {
3637 var topInt, topPersistentInt, subCommandInt, appOverrideInt int64
3638 var appFlag string
3639 var appRequiredFlag string
3640 var appOverrideCmdInt int64
3641 var appSliceFloat64 []float64
3642 var persistentCommandSliceInt []int64
3643 var persistentFlagActionCount int64
3644
3645 cmd := &Command{
3646 Flags: []Flag{
3647 &StringFlag{
3648 Name: "persistentCommandFlag",
3649 Destination: &appFlag,
3650 Action: func(context.Context, *Command, string) error {
3651 persistentFlagActionCount++
3652 return nil
3653 },
3654 },
3655 &Int64SliceFlag{
3656 Name: "persistentCommandSliceFlag",
3657 Destination: &persistentCommandSliceInt,
3658 },
3659 &FloatSliceFlag{
3660 Name: "persistentCommandFloatSliceFlag",
3661 Value: []float64{11.3, 12.5},
3662 },
3663 &Int64Flag{
3664 Name: "persistentCommandOverrideFlag",
3665 Destination: &appOverrideInt,
3666 },
3667 &StringFlag{
3668 Name: "persistentRequiredCommandFlag",
3669 Required: true,
3670 Destination: &appRequiredFlag,
3671 },
3672 },
3673 Commands: []*Command{
3674 {
3675 Name: "cmd",
3676 Flags: []Flag{
3677 &Int64Flag{
3678 Name: "cmdFlag",
3679 Destination: &topInt,
3680 Local: true,
3681 },
3682 &Int64Flag{
3683 Name: "cmdPersistentFlag",
3684 Destination: &topPersistentInt,
3685 },
3686 &Int64Flag{
3687 Name: "paof",
3688 Aliases: []string{"persistentCommandOverrideFlag"},
3689 Destination: &appOverrideCmdInt,
3690 Local: true,
3691 },
3692 },
3693 Commands: []*Command{
3694 {
3695 Name: "subcmd",
3696 Flags: []Flag{
3697 &Int64Flag{
3698 Name: "cmdFlag",
3699 Destination: &subCommandInt,
3700 Local: true,
3701 },
3702 },
3703 Action: func(_ context.Context, cmd *Command) error {
3704 appSliceFloat64 = cmd.FloatSlice("persistentCommandFloatSliceFlag")
3705 return nil
3706 },
3707 },
3708 },
3709 },
3710 },
3711 }
3712
3713 err := cmd.Run(buildTestContext(t), []string{
3714 "app",
3715 "--persistentCommandFlag", "hello",
3716 "--persistentCommandSliceFlag", "100",
3717 "--persistentCommandOverrideFlag", "102",
3718 "cmd",
3719 "--cmdFlag", "12",
3720 "--persistentCommandSliceFlag", "102",
3721 "--persistentCommandFloatSliceFlag", "102.455",
3722 "--paof", "105",
3723 "--persistentRequiredCommandFlag", "hellor",
3724 "subcmd",
3725 "--cmdPersistentFlag", "20",
3726 "--cmdFlag", "11",
3727 "--persistentCommandFlag", "bar",
3728 "--persistentCommandSliceFlag", "130",
3729 "--persistentCommandFloatSliceFlag", "3.1445",
3730 })
3731
3732 require.NoError(t, err)
3733
3734 assert.Equal(t, "bar", appFlag)
3735 assert.Equal(t, "hellor", appRequiredFlag)
3736 assert.Equal(t, int64(12), topInt)
3737 assert.Equal(t, int64(20), topPersistentInt)
3738
3739 // this should be changed from app since
3740 // cmd overrides it
3741 assert.Equal(t, int64(102), appOverrideInt)
3742 assert.Equal(t, int64(11), subCommandInt)
3743 assert.Equal(t, int64(105), appOverrideCmdInt)
3744 assert.Equal(t, []int64{100, 102, 130}, persistentCommandSliceInt)
3745 assert.Equal(t, []float64{102.455, 3.1445}, appSliceFloat64)
3746 assert.Equal(t, int64(2), persistentFlagActionCount, "Expected persistent flag action to be called 2 times")
3747 }
3748
3749 func TestPersistentFlagIsSet(t *testing.T) {
3750 result := ""
3751 resultIsSet := false
3752
3753 app := &Command{
3754 Name: "root",
3755 Flags: []Flag{
3756 &StringFlag{
3757 Name: "result",
3758 },
3759 },
3760 Commands: []*Command{
3761 {
3762 Name: "sub",
3763 Action: func(_ context.Context, cmd *Command) error {
3764 result = cmd.String("result")
3765 resultIsSet = cmd.IsSet("result")
3766 return nil
3767 },
3768 },
3769 },
3770 }
3771
3772 err := app.Run(context.Background(), []string{"root", "--result", "before", "sub"})
3773 require.NoError(t, err)
3774 require.Equal(t, "before", result)
3775 require.True(t, resultIsSet)
3776
3777 err = app.Run(context.Background(), []string{"root", "sub", "--result", "after"})
3778 require.NoError(t, err)
3779 require.Equal(t, "after", result)
3780 require.True(t, resultIsSet)
3781 }
3782
3783 func TestDuplicatePersistentFlagUsesEnvSource(t *testing.T) {
3784 t.Setenv("APP_RESULT", "from-env")
3785
3786 resultFlag := &StringFlag{
3787 Name: "result",
3788 Sources: EnvVars("APP_RESULT"),
3789 Required: true,
3790 }
3791
3792 var beforeResult string
3793 var actionResult string
3794 app := &Command{
3795 Name: "root",
3796 Flags: []Flag{
3797 resultFlag,
3798 },
3799 Before: func(_ context.Context, cmd *Command) (context.Context, error) {
3800 beforeResult = cmd.String("result")
3801 return nil, nil
3802 },
3803 Commands: []*Command{
3804 {
3805 Name: "sub",
3806 Flags: []Flag{
3807 resultFlag,
3808 },
3809 Action: func(_ context.Context, cmd *Command) error {
3810 actionResult = cmd.String("result")
3811 return nil
3812 },
3813 },
3814 },
3815 }
3816
3817 err := app.Run(context.Background(), []string{"root", "sub"})
3818 require.NoError(t, err)
3819 require.Equal(t, "from-env", beforeResult)
3820 require.Equal(t, "from-env", actionResult)
3821 require.True(t, app.IsSet("result"))
3822 require.True(t, app.Command("sub").IsSet("result"))
3823 }
3824
3825 func TestRequiredFlagDelayed(t *testing.T) {
3826 sf := &StringFlag{
3827 Name: "result",
3828 Required: true,
3829 }
3830
3831 expectedErr := &errRequiredFlags{
3832 missingFlags: []string{sf.Name},
3833 }
3834
3835 tests := []struct {
3836 name string
3837 args []string
3838 errExpected error
3839 }{
3840 {
3841 name: "leaf help",
3842 args: []string{"root", "sub", "-h"},
3843 errExpected: nil,
3844 },
3845 {
3846 name: "leaf action",
3847 args: []string{"root", "sub"},
3848 errExpected: expectedErr,
3849 },
3850 {
3851 name: "leaf flags set",
3852 args: []string{"root", "sub", "--if", "10"},
3853 errExpected: expectedErr,
3854 },
3855 {
3856 name: "leaf invalid flags set",
3857 args: []string{"root", "sub", "--xx"},
3858 errExpected: expectedErr,
3859 },
3860 }
3861
3862 app := &Command{
3863 Name: "root",
3864 Flags: []Flag{
3865 sf,
3866 },
3867 Commands: []*Command{
3868 {
3869 Name: "sub",
3870 Flags: []Flag{
3871 &Int64Flag{
3872 Name: "if",
3873 Required: true,
3874 },
3875 },
3876 Action: func(ctx context.Context, c *Command) error {
3877 return nil
3878 },
3879 },
3880 },
3881 }
3882
3883 for _, test := range tests {
3884 t.Run(test.name, func(t *testing.T) {
3885 err := app.Run(context.Background(), test.args)
3886 if test.errExpected == nil {
3887 require.NoError(t, err)
3888 } else {
3889 require.ErrorAs(t, err, &test.errExpected)
3890 }
3891 })
3892 }
3893 }
3894
3895 func TestRequiredPersistentFlag(t *testing.T) {
3896 app := &Command{
3897 Name: "root",
3898 Flags: []Flag{
3899 &StringFlag{
3900 Name: "result",
3901 Required: true,
3902 },
3903 },
3904 Commands: []*Command{
3905 {
3906 Name: "sub",
3907 Action: func(ctx context.Context, c *Command) error {
3908 return nil
3909 },
3910 },
3911 },
3912 }
3913
3914 err := app.Run(context.Background(), []string{"root", "sub"})
3915 require.Error(t, err)
3916
3917 err = app.Run(context.Background(), []string{"root", "sub", "--result", "after"})
3918 require.NoError(t, err)
3919 }
3920
3921 func TestFlagDuplicates(t *testing.T) {
3922 tests := []struct {
3923 name string
3924 args []string
3925 errExpected bool
3926 }{
3927 {
3928 name: "all args present once",
3929 args: []string{"foo", "--sflag", "hello", "--isflag", "1", "--isflag", "2", "--fsflag", "2.0", "--iflag", "10", "--bifflag"},
3930 },
3931 {
3932 name: "duplicate non slice flag(duplicatable)",
3933 args: []string{"foo", "--sflag", "hello", "--isflag", "1", "--isflag", "2", "--fsflag", "2.0", "--iflag", "10", "--iflag", "20"},
3934 },
3935 {
3936 name: "duplicate non slice flag(non duplicatable)",
3937 args: []string{"foo", "--sflag", "hello", "--isflag", "1", "--isflag", "2", "--fsflag", "2.0", "--iflag", "10", "--sflag", "trip"},
3938 errExpected: true,
3939 },
3940 {
3941 name: "duplicate slice flag(non duplicatable)",
3942 args: []string{"foo", "--sflag", "hello", "--isflag", "1", "--isflag", "2", "--fsflag", "2.0", "--fsflag", "3.0", "--iflag", "10"},
3943 errExpected: true,
3944 },
3945 {
3946 name: "duplicate bool inverse flag(non duplicatable)",
3947 args: []string{"foo", "--bifflag", "--bifflag"},
3948 errExpected: true,
3949 },
3950 }
3951
3952 for _, test := range tests {
3953 t.Run(test.name, func(t *testing.T) {
3954 cmd := &Command{
3955 Flags: []Flag{
3956 &StringFlag{
3957 Name: "sflag",
3958 OnlyOnce: true,
3959 },
3960 &Int64SliceFlag{
3961 Name: "isflag",
3962 },
3963 &FloatSliceFlag{
3964 Name: "fsflag",
3965 OnlyOnce: true,
3966 },
3967 &BoolWithInverseFlag{
3968 Name: "bifflag",
3969 OnlyOnce: true,
3970 },
3971 &Int64Flag{
3972 Name: "iflag",
3973 },
3974 },
3975 Action: func(context.Context, *Command) error {
3976 return nil
3977 },
3978 }
3979
3980 err := cmd.Run(buildTestContext(t), test.args)
3981 if test.errExpected {
3982 assert.Error(t, err)
3983 } else {
3984 assert.NoError(t, err)
3985 }
3986 })
3987 }
3988 }
3989
3990 func TestShorthandCommand(t *testing.T) {
3991 af := func(p *int) ActionFunc {
3992 return func(context.Context, *Command) error {
3993 *p = *p + 1
3994 return nil
3995 }
3996 }
3997
3998 var cmd1, cmd2 int
3999
4000 cmd := &Command{
4001 PrefixMatchCommands: true,
4002 Commands: []*Command{
4003 {
4004 Name: "cthdisd",
4005 Aliases: []string{"cth"},
4006 Action: af(&cmd1),
4007 },
4008 {
4009 Name: "cthertoop",
4010 Aliases: []string{"cer"},
4011 Action: af(&cmd2),
4012 },
4013 },
4014 }
4015
4016 err := cmd.Run(buildTestContext(t), []string{"foo", "cth"})
4017 assert.NoError(t, err)
4018 assert.True(t, cmd1 == 1 && cmd2 == 0, "Expected command1 to be triggered once")
4019
4020 cmd1 = 0
4021 cmd2 = 0
4022
4023 err = cmd.Run(buildTestContext(t), []string{"foo", "cthd"})
4024 assert.NoError(t, err)
4025 assert.True(t, cmd1 == 1 && cmd2 == 0, "Expected command1 to be triggered once")
4026
4027 cmd1 = 0
4028 cmd2 = 0
4029
4030 err = cmd.Run(buildTestContext(t), []string{"foo", "cthe"})
4031 assert.NoError(t, err)
4032 assert.True(t, cmd1 == 1 && cmd2 == 0, "Expected command1 to be triggered once")
4033
4034 cmd1 = 0
4035 cmd2 = 0
4036
4037 err = cmd.Run(buildTestContext(t), []string{"foo", "cthert"})
4038 assert.NoError(t, err)
4039 assert.True(t, cmd1 == 0 && cmd2 == 1, "Expected command1 to be triggered once")
4040
4041 cmd1 = 0
4042 cmd2 = 0
4043
4044 err = cmd.Run(buildTestContext(t), []string{"foo", "cthet"})
4045 assert.NoError(t, err)
4046 assert.True(t, cmd1 == 0 && cmd2 == 1, "Expected command1 to be triggered once")
4047 }
4048
4049 func TestCommand_Int(t *testing.T) {
4050 pCmd := &Command{
4051 Flags: []Flag{
4052 &Int64Flag{
4053 Name: "myflag",
4054 Value: 12,
4055 },
4056 },
4057 }
4058 cmd := &Command{
4059 Flags: []Flag{
4060 &Int64Flag{
4061 Name: "top-flag",
4062 Value: 13,
4063 },
4064 },
4065 parent: pCmd,
4066 }
4067
4068 require.Equal(t, int64(12), cmd.Int64("myflag"))
4069 require.Equal(t, int64(13), cmd.Int64("top-flag"))
4070 }
4071
4072 func TestCommand_Uint(t *testing.T) {
4073 pCmd := &Command{
4074 Flags: []Flag{
4075 &Uint64Flag{
4076 Name: "myflagUint",
4077 Value: 13,
4078 },
4079 },
4080 }
4081 cmd := &Command{
4082 Flags: []Flag{
4083 &Uint64Flag{
4084 Name: "top-flag",
4085 Value: 14,
4086 },
4087 },
4088 parent: pCmd,
4089 }
4090
4091 require.Equal(t, uint64(13), cmd.Uint64("myflagUint"))
4092 require.Equal(t, uint64(14), cmd.Uint64("top-flag"))
4093 }
4094
4095 func TestCommand_Float64(t *testing.T) {
4096 pCmd := &Command{
4097 Flags: []Flag{
4098 &FloatFlag{
4099 Name: "myflag",
4100 Value: 17,
4101 },
4102 },
4103 }
4104 cmd := &Command{
4105 Flags: []Flag{
4106 &FloatFlag{
4107 Name: "top-flag",
4108 Value: 18,
4109 },
4110 },
4111 parent: pCmd,
4112 }
4113
4114 r := require.New(t)
4115 r.Equal(float64(17), cmd.Float("myflag"))
4116 r.Equal(float64(18), cmd.Float("top-flag"))
4117 }
4118
4119 func TestCommand_Duration(t *testing.T) {
4120 pCmd := &Command{
4121 Flags: []Flag{
4122 &DurationFlag{
4123 Name: "myflag",
4124 Value: 12 * time.Second,
4125 },
4126 },
4127 }
4128 cmd := &Command{
4129 Flags: []Flag{
4130 &DurationFlag{
4131 Name: "top-flag",
4132 Value: 13 * time.Second,
4133 },
4134 },
4135 parent: pCmd,
4136 }
4137
4138 r := require.New(t)
4139 r.Equal(12*time.Second, cmd.Duration("myflag"))
4140 r.Equal(13*time.Second, cmd.Duration("top-flag"))
4141 }
4142
4143 func TestCommand_Timestamp(t *testing.T) {
4144 t1 := time.Time{}.Add(12 * time.Second)
4145 t2 := time.Time{}.Add(13 * time.Second)
4146
4147 cmd := &Command{
4148 Name: "hello",
4149 Flags: []Flag{
4150 &TimestampFlag{
4151 Name: "myflag",
4152 Value: t1,
4153 },
4154 },
4155 Action: func(ctx context.Context, c *Command) error {
4156 return nil
4157 },
4158 }
4159
4160 pCmd := &Command{
4161 Flags: []Flag{
4162 &TimestampFlag{
4163 Name: "top-flag",
4164 Value: t2,
4165 },
4166 },
4167 Commands: []*Command{
4168 cmd,
4169 },
4170 }
4171
4172 err := pCmd.Run(context.Background(), []string{"foo", "hello"})
4173 assert.NoError(t, err)
4174
4175 r := require.New(t)
4176 r.Equal(t1, cmd.Timestamp("myflag"))
4177 r.Equal(t2, cmd.Timestamp("top-flag"))
4178 }
4179
4180 func TestCommand_String(t *testing.T) {
4181 pCmd := &Command{
4182 Flags: []Flag{
4183 &StringFlag{
4184 Name: "myflag",
4185 Value: "hello world",
4186 },
4187 },
4188 }
4189 cmd := &Command{
4190 Flags: []Flag{
4191 &StringFlag{
4192 Name: "top-flag",
4193 Value: "hai veld",
4194 },
4195 },
4196 parent: pCmd,
4197 }
4198
4199 r := require.New(t)
4200 r.Equal("hello world", cmd.String("myflag"))
4201 r.Equal("hai veld", cmd.String("top-flag"))
4202
4203 r.Equal("hai veld", cmd.String("top-flag"))
4204 }
4205
4206 func TestCommand_Bool(t *testing.T) {
4207 pCmd := &Command{
4208 Flags: []Flag{
4209 &BoolFlag{
4210 Name: "myflag",
4211 },
4212 },
4213 }
4214 cmd := &Command{
4215 Flags: []Flag{
4216 &BoolFlag{
4217 Name: "top-flag",
4218 Value: true,
4219 },
4220 },
4221 parent: pCmd,
4222 }
4223
4224 r := require.New(t)
4225 r.False(cmd.Bool("myflag"))
4226 r.True(cmd.Bool("top-flag"))
4227 }
4228
4229 func TestCommand_Value(t *testing.T) {
4230 subCmd := &Command{
4231 Name: "test",
4232 Flags: []Flag{
4233 &Int64Flag{
4234 Name: "myflag",
4235 Usage: "doc",
4236 Aliases: []string{"m", "mf"},
4237 },
4238 },
4239 Action: func(ctx context.Context, c *Command) error {
4240 return nil
4241 },
4242 }
4243
4244 cmd := &Command{
4245 Flags: []Flag{
4246 &Int64Flag{
4247 Name: "top-flag",
4248 Usage: "doc",
4249 Aliases: []string{"t", "tf"},
4250 },
4251 },
4252 Commands: []*Command{
4253 subCmd,
4254 },
4255 }
4256 t.Run("flag name", func(t *testing.T) {
4257 r := require.New(t)
4258 err := cmd.Run(buildTestContext(t), []string{"main", "--top-flag", "13", "test", "--myflag", "14"})
4259
4260 r.NoError(err)
4261 r.Equal(int64(13), cmd.Value("top-flag"))
4262 r.Equal(int64(13), cmd.Value("t"))
4263 r.Equal(int64(13), cmd.Value("tf"))
4264
4265 r.Equal(int64(14), subCmd.Value("myflag"))
4266 r.Equal(int64(14), subCmd.Value("m"))
4267 r.Equal(int64(14), subCmd.Value("mf"))
4268 })
4269
4270 t.Run("flag aliases", func(t *testing.T) {
4271 r := require.New(t)
4272 err := cmd.Run(buildTestContext(t), []string{"main", "-tf", "15", "test", "-m", "16"})
4273
4274 r.NoError(err)
4275 r.Equal(int64(15), cmd.Value("top-flag"))
4276 r.Equal(int64(15), cmd.Value("t"))
4277 r.Equal(int64(15), cmd.Value("tf"))
4278
4279 r.Equal(int64(16), subCmd.Value("myflag"))
4280 r.Equal(int64(16), subCmd.Value("m"))
4281 r.Equal(int64(16), subCmd.Value("mf"))
4282 r.Nil(cmd.Value("unknown-flag"))
4283 })
4284 }
4285
4286 func TestCommand_Value_InvalidFlagAccessHandler(t *testing.T) {
4287 var flagName string
4288 cmd := &Command{
4289 InvalidFlagAccessHandler: func(_ context.Context, _ *Command, name string) {
4290 flagName = name
4291 },
4292 Commands: []*Command{
4293 {
4294 Name: "command",
4295 Commands: []*Command{
4296 {
4297 Name: "subcommand",
4298 Action: func(_ context.Context, cmd *Command) error {
4299 cmd.Value("missing")
4300 return nil
4301 },
4302 },
4303 },
4304 },
4305 },
4306 }
4307
4308 r := require.New(t)
4309
4310 r.NoError(cmd.Run(buildTestContext(t), []string{"run", "command", "subcommand"}))
4311 r.Equal("missing", flagName)
4312 }
4313
4314 func TestCommand_Args(t *testing.T) {
4315 cmd := &Command{
4316 Flags: []Flag{
4317 &BoolFlag{
4318 Name: "myflag",
4319 },
4320 },
4321 }
4322 _ = cmd.Run(context.Background(), []string{"", "--myflag", "bat", "baz"})
4323
4324 r := require.New(t)
4325 r.Equal(2, cmd.Args().Len())
4326 r.True(cmd.Bool("myflag"))
4327 r.Equal(2, cmd.NArg())
4328 }
4329
4330 func TestCommand_IsSet(t *testing.T) {
4331 cmd := &Command{
4332 Name: "frob",
4333 Flags: []Flag{
4334 &BoolFlag{
4335 Name: "one-flag",
4336 },
4337 &BoolFlag{
4338 Name: "two-flag",
4339 },
4340 &StringFlag{
4341 Name: "three-flag",
4342 Value: "hello world",
4343 },
4344 },
4345 }
4346 pCmd := &Command{
4347 Name: "root",
4348 Flags: []Flag{
4349 &BoolFlag{
4350 Name: "top-flag",
4351 Value: true,
4352 },
4353 },
4354 Commands: []*Command{
4355 cmd,
4356 },
4357 }
4358
4359 r := require.New(t)
4360
4361 r.NoError(pCmd.Run(context.Background(), []string{"foo", "frob", "--one-flag", "--top-flag", "--two-flag", "--three-flag", "dds"}))
4362
4363 r.True(cmd.IsSet("one-flag"))
4364 r.True(cmd.IsSet("two-flag"))
4365 r.True(cmd.IsSet("three-flag"))
4366 r.True(cmd.IsSet("top-flag"))
4367 r.False(cmd.IsSet("bogus"))
4368 }
4369
4370 // XXX Corresponds to hack in context.IsSet for flags with EnvVar field
4371 // Should be moved to `flag_test` in v2
4372 func TestCommand_IsSet_fromEnv(t *testing.T) {
4373 var (
4374 timeoutIsSet, tIsSet bool
4375 noEnvVarIsSet, nIsSet bool
4376 passwordIsSet, pIsSet bool
4377 unparsableIsSet, uIsSet bool
4378 )
4379
4380 t.Setenv("APP_TIMEOUT_SECONDS", "15.5")
4381 t.Setenv("APP_PASSWORD", "")
4382
4383 cmd := &Command{
4384 Flags: []Flag{
4385 &FloatFlag{Name: "timeout", Aliases: []string{"t"}, Local: true, Sources: EnvVars("APP_TIMEOUT_SECONDS")},
4386 &StringFlag{Name: "password", Aliases: []string{"p"}, Local: true, Sources: EnvVars("APP_PASSWORD")},
4387 &FloatFlag{Name: "unparsable", Aliases: []string{"u"}, Local: true, Sources: EnvVars("APP_UNPARSABLE")},
4388 &FloatFlag{Name: "no-env-var", Aliases: []string{"n"}, Local: true},
4389 },
4390 Action: func(_ context.Context, cmd *Command) error {
4391 timeoutIsSet = cmd.IsSet("timeout")
4392 tIsSet = cmd.IsSet("t")
4393 passwordIsSet = cmd.IsSet("password")
4394 pIsSet = cmd.IsSet("p")
4395 unparsableIsSet = cmd.IsSet("unparsable")
4396 uIsSet = cmd.IsSet("u")
4397 noEnvVarIsSet = cmd.IsSet("no-env-var")
4398 nIsSet = cmd.IsSet("n")
4399 return nil
4400 },
4401 }
4402
4403 r := require.New(t)
4404
4405 r.NoError(cmd.Run(buildTestContext(t), []string{"run"}))
4406 r.True(timeoutIsSet)
4407 r.True(tIsSet)
4408 r.True(passwordIsSet)
4409 r.True(pIsSet)
4410 r.False(noEnvVarIsSet)
4411 r.False(nIsSet)
4412
4413 t.Setenv("APP_UNPARSABLE", "foobar")
4414
4415 r.Error(cmd.Run(buildTestContext(t), []string{"run"}))
4416 r.False(unparsableIsSet)
4417 r.False(uIsSet)
4418 }
4419
4420 func TestCommand_NumFlags(t *testing.T) {
4421 rootCmd := &Command{
4422 Flags: []Flag{
4423 &BoolFlag{
4424 Name: "myflagGlobal",
4425 Value: true,
4426 },
4427 },
4428 }
4429 cmd := &Command{
4430 Flags: []Flag{
4431 &BoolFlag{
4432 Name: "myflag",
4433 },
4434 &StringFlag{
4435 Name: "otherflag",
4436 Value: "hello world",
4437 },
4438 },
4439 }
4440
4441 _ = cmd.Run(context.Background(), []string{"", "--myflag", "--otherflag=foo"})
4442 _ = rootCmd.Run(context.Background(), []string{"", "--myflagGlobal"})
4443 require.Equal(t, 2, cmd.NumFlags())
4444 actualFlags := cmd.LocalFlagNames()
4445 sort.Strings(actualFlags)
4446
4447 require.Equal(t, []string{"myflag", "otherflag"}, actualFlags)
4448
4449 actualFlags = cmd.FlagNames()
4450 sort.Strings(actualFlags)
4451
4452 require.Equal(t, []string{"myflag", "otherflag"}, actualFlags)
4453
4454 cmd.parent = rootCmd
4455 lineage := cmd.Lineage()
4456
4457 r := require.New(t)
4458 r.Equal(2, len(lineage))
4459 r.Equal(cmd, lineage[0])
4460 r.Equal(rootCmd, lineage[1])
4461 }
4462
4463 func TestCommand_Set(t *testing.T) {
4464 cmd := &Command{
4465 Flags: []Flag{
4466 &Int64Flag{
4467 Name: "int",
4468 Value: 5,
4469 },
4470 },
4471 }
4472 r := require.New(t)
4473
4474 r.False(cmd.IsSet("int"))
4475 r.NoError(cmd.Set("int", "1"))
4476 r.Equal(int64(1), cmd.Int64("int"))
4477 r.True(cmd.IsSet("int"))
4478 }
4479
4480 func TestCommand_Set_InvalidFlagAccessHandler(t *testing.T) {
4481 var flagName string
4482 cmd := &Command{
4483 InvalidFlagAccessHandler: func(_ context.Context, _ *Command, name string) {
4484 flagName = name
4485 },
4486 }
4487
4488 r := require.New(t)
4489
4490 r.True(cmd.Set("missing", "") != nil)
4491 r.Equal("missing", flagName)
4492 }
4493
4494 func TestCommand_lookupFlag(t *testing.T) {
4495 pCmd := &Command{
4496 Flags: []Flag{
4497 &BoolFlag{
4498 Name: "top-flag",
4499 Value: true,
4500 },
4501 },
4502 }
4503 cmd := &Command{
4504 Flags: []Flag{
4505 &BoolFlag{
4506 Name: "local-flag",
4507 },
4508 },
4509 }
4510 _ = cmd.Run(context.Background(), []string{"--local-flag"})
4511 pCmd.Commands = []*Command{cmd}
4512 _ = pCmd.Run(context.Background(), []string{"--top-flag"})
4513
4514 r := require.New(t)
4515
4516 fs := cmd.lookupFlag("top-flag")
4517 r.Equal(pCmd.Flags[0], fs)
4518
4519 fs = cmd.lookupFlag("local-flag")
4520 r.Equal(cmd.Flags[0], fs)
4521 r.Nil(cmd.lookupFlag("frob"))
4522 }
4523
4524 func TestCommandAttributeAccessing(t *testing.T) {
4525 tdata := []struct {
4526 testCase string
4527 setBoolInput string
4528 ctxBoolInput string
4529 parent *Command
4530 }{
4531 {
4532 testCase: "empty",
4533 setBoolInput: "",
4534 ctxBoolInput: "",
4535 },
4536 {
4537 testCase: "empty_with_background_context",
4538 setBoolInput: "",
4539 ctxBoolInput: "",
4540 parent: &Command{},
4541 },
4542 {
4543 testCase: "empty_set_bool_and_present_ctx_bool",
4544 setBoolInput: "",
4545 ctxBoolInput: "ctx-bool",
4546 },
4547 {
4548 testCase: "present_set_bool_and_present_ctx_bool_with_background_context",
4549 setBoolInput: "",
4550 ctxBoolInput: "ctx-bool",
4551 parent: &Command{},
4552 },
4553 {
4554 testCase: "present_set_bool_and_present_ctx_bool",
4555 setBoolInput: "ctx-bool",
4556 ctxBoolInput: "ctx-bool",
4557 },
4558 {
4559 testCase: "present_set_bool_and_present_ctx_bool_with_background_context",
4560 setBoolInput: "ctx-bool",
4561 ctxBoolInput: "ctx-bool",
4562 parent: &Command{},
4563 },
4564 {
4565 testCase: "present_set_bool_and_different_ctx_bool",
4566 setBoolInput: "ctx-bool",
4567 ctxBoolInput: "not-ctx-bool",
4568 },
4569 {
4570 testCase: "present_set_bool_and_different_ctx_bool_with_background_context",
4571 setBoolInput: "ctx-bool",
4572 ctxBoolInput: "not-ctx-bool",
4573 parent: &Command{},
4574 },
4575 }
4576
4577 for _, test := range tdata {
4578 t.Run(test.testCase, func(t *testing.T) {
4579 cmd := &Command{parent: test.parent}
4580
4581 require.False(t, cmd.Bool(test.ctxBoolInput))
4582 })
4583 }
4584 }
4585
4586 func TestCheckRequiredFlags(t *testing.T) {
4587 tdata := []struct {
4588 testCase string
4589 parseInput []string
4590 envVarInput [2]string
4591 flags []Flag
4592 expectedAnError bool
4593 expectedErrorContents []string
4594 }{
4595 {
4596 testCase: "empty",
4597 },
4598 {
4599 testCase: "optional",
4600 flags: []Flag{
4601 &StringFlag{Name: "optionalFlag"},
4602 },
4603 },
4604 {
4605 testCase: "required",
4606 flags: []Flag{
4607 &StringFlag{Name: "requiredFlag", Required: true},
4608 },
4609 expectedAnError: true,
4610 expectedErrorContents: []string{"requiredFlag"},
4611 },
4612 {
4613 testCase: "required_and_present",
4614 flags: []Flag{
4615 &StringFlag{Name: "requiredFlag", Required: true},
4616 },
4617 parseInput: []string{"--requiredFlag", "myinput"},
4618 },
4619 {
4620 testCase: "required_and_present_via_env_var",
4621 flags: []Flag{
4622 &StringFlag{Name: "requiredFlag", Required: true, Sources: EnvVars("REQUIRED_FLAG")},
4623 },
4624 envVarInput: [2]string{"REQUIRED_FLAG", "true"},
4625 },
4626 {
4627 testCase: "required_and_optional",
4628 flags: []Flag{
4629 &StringFlag{Name: "requiredFlag", Required: true},
4630 &StringFlag{Name: "optionalFlag"},
4631 },
4632 expectedAnError: true,
4633 },
4634 {
4635 testCase: "required_and_optional_and_optional_present",
4636 flags: []Flag{
4637 &StringFlag{Name: "requiredFlag", Required: true},
4638 &StringFlag{Name: "optionalFlag"},
4639 },
4640 parseInput: []string{"--optionalFlag", "myinput"},
4641 expectedAnError: true,
4642 },
4643 {
4644 testCase: "required_and_optional_and_optional_present_via_env_var",
4645 flags: []Flag{
4646 &StringFlag{Name: "requiredFlag", Required: true},
4647 &StringFlag{Name: "optionalFlag", Sources: EnvVars("OPTIONAL_FLAG")},
4648 },
4649 envVarInput: [2]string{"OPTIONAL_FLAG", "true"},
4650 expectedAnError: true,
4651 },
4652 {
4653 testCase: "required_and_optional_and_required_present",
4654 flags: []Flag{
4655 &StringFlag{Name: "requiredFlag", Required: true},
4656 &StringFlag{Name: "optionalFlag"},
4657 },
4658 parseInput: []string{"--requiredFlag", "myinput"},
4659 },
4660 {
4661 testCase: "two_required",
4662 flags: []Flag{
4663 &StringFlag{Name: "requiredFlagOne", Required: true},
4664 &StringFlag{Name: "requiredFlagTwo", Required: true},
4665 },
4666 expectedAnError: true,
4667 expectedErrorContents: []string{"requiredFlagOne", "requiredFlagTwo"},
4668 },
4669 {
4670 testCase: "two_required_and_one_present",
4671 flags: []Flag{
4672 &StringFlag{Name: "requiredFlag", Required: true},
4673 &StringFlag{Name: "requiredFlagTwo", Required: true},
4674 },
4675 parseInput: []string{"--requiredFlag", "myinput"},
4676 expectedAnError: true,
4677 },
4678 {
4679 testCase: "two_required_and_both_present",
4680 flags: []Flag{
4681 &StringFlag{Name: "requiredFlag", Required: true},
4682 &StringFlag{Name: "requiredFlagTwo", Required: true},
4683 },
4684 parseInput: []string{"--requiredFlag", "myinput", "--requiredFlagTwo", "myinput"},
4685 },
4686 {
4687 testCase: "required_flag_with_short_name",
4688 flags: []Flag{
4689 &StringSliceFlag{Name: "names", Aliases: []string{"N"}, Required: true},
4690 },
4691 parseInput: []string{"-N", "asd", "-N", "qwe"},
4692 },
4693 {
4694 testCase: "required_flag_with_multiple_short_names",
4695 flags: []Flag{
4696 &StringSliceFlag{Name: "names", Aliases: []string{"N", "n"}, Required: true},
4697 },
4698 parseInput: []string{"-n", "asd", "-n", "qwe"},
4699 },
4700 {
4701 testCase: "required_flag_with_short_alias_not_printed_on_error",
4702 expectedAnError: true,
4703 expectedErrorContents: []string{"Required flag \"names\" not set"},
4704 flags: []Flag{
4705 &StringSliceFlag{Name: "names", Aliases: []string{"n"}, Required: true},
4706 },
4707 },
4708 {
4709 testCase: "required_flag_with_one_character",
4710 expectedAnError: true,
4711 expectedErrorContents: []string{"Required flag \"n\" not set"},
4712 flags: []Flag{
4713 &StringFlag{Name: "n", Required: true},
4714 },
4715 },
4716 }
4717
4718 for _, test := range tdata {
4719 t.Run(test.testCase, func(t *testing.T) {
4720 // setup
4721 if test.envVarInput[0] != "" {
4722 t.Setenv(test.envVarInput[0], test.envVarInput[1])
4723 }
4724
4725 cmd := &Command{
4726 Name: "foo",
4727 Flags: test.flags,
4728 }
4729 args := []string{"foo"}
4730 args = append(args, test.parseInput...)
4731 _ = cmd.Run(context.Background(), args)
4732
4733 err := cmd.checkAllRequiredFlags()
4734
4735 // assertions
4736 if test.expectedAnError {
4737 assert.NotNil(t, err)
4738 } else {
4739 assert.Nil(t, err)
4740 }
4741 for _, errString := range test.expectedErrorContents {
4742 if err != nil {
4743 assert.ErrorContains(t, err, errString)
4744 }
4745 }
4746 })
4747 }
4748 }
4749
4750 func TestCheckRequiredFlagsWithOnUsageError(t *testing.T) {
4751 expectedError := errors.New("OnUsageError")
4752 cmd := &Command{
4753 Name: "foo",
4754 Flags: []Flag{
4755 &StringFlag{Name: "requiredFlag", Required: true},
4756 },
4757 OnUsageError: func(_ context.Context, _ *Command, _ error, _ bool) error {
4758 return expectedError
4759 },
4760 }
4761 actualError := cmd.Run(buildTestContext(t), []string{"requiredFlag"})
4762 require.ErrorIs(t, actualError, expectedError)
4763 }
4764
4765 func TestCommand_ParentCommand_Set(t *testing.T) {
4766 cmd := &Command{
4767 parent: &Command{
4768 Flags: []Flag{
4769 &StringFlag{
4770 Name: "Name",
4771 },
4772 },
4773 },
4774 }
4775
4776 err := cmd.Set("Name", "aaa")
4777 assert.NoError(t, err)
4778 }
4779
4780 func TestCommandStringDashOption(t *testing.T) {
4781 tests := []struct {
4782 name string
4783 shortOptionHandling bool
4784 args []string
4785 }{
4786 {
4787 name: "double dash separate value",
4788 args: []string{"foo", "--bar", "-", "test"},
4789 },
4790 {
4791 name: "single dash separate value",
4792 args: []string{"foo", "-bar", "-", "test"},
4793 },
4794 /*{
4795 name: "single dash combined value",
4796 args: []string{"foo", "-b-", "test"},
4797 shortOptionHandling: true,
4798 },*/
4799 }
4800
4801 for _, test := range tests {
4802 t.Run(test.name, func(t *testing.T) {
4803 cmd := &Command{
4804 Name: "foo",
4805 UseShortOptionHandling: test.shortOptionHandling,
4806 Flags: []Flag{
4807 &StringFlag{
4808 Name: "bar",
4809 Aliases: []string{"b"},
4810 },
4811 },
4812 Action: func(ctx context.Context, c *Command) error {
4813 return nil
4814 },
4815 }
4816
4817 err := cmd.Run(buildTestContext(t), test.args)
4818 assert.NoError(t, err)
4819
4820 assert.Equal(t, "-", cmd.String("b"))
4821 })
4822 }
4823 }
4824
4825 func TestCommandReadArgsFromStdIn(t *testing.T) {
4826 tests := []struct {
4827 name string
4828 input string
4829 args []string
4830 expectedInt int64
4831 expectedFloat float64
4832 expectedSlice []string
4833 expectError bool
4834 }{
4835 {
4836 name: "empty",
4837 input: "",
4838 args: []string{"foo"},
4839 expectedInt: 0,
4840 expectedFloat: 0.0,
4841 expectedSlice: []string{},
4842 },
4843 {
4844 name: "empty2",
4845 input: `
4846
4847 `,
4848 args: []string{"foo"},
4849 expectedInt: 0,
4850 expectedFloat: 0.0,
4851 expectedSlice: []string{},
4852 },
4853 {
4854 name: "intflag-from-input",
4855 input: "--if=100",
4856 args: []string{"foo"},
4857 expectedInt: 100,
4858 expectedFloat: 0.0,
4859 expectedSlice: []string{},
4860 },
4861 {
4862 name: "intflag-from-input2",
4863 input: `
4864 --if
4865
4866 100`,
4867 args: []string{"foo"},
4868 expectedInt: 100,
4869 expectedFloat: 0.0,
4870 expectedSlice: []string{},
4871 },
4872 {
4873 name: "multiflag-from-input",
4874 input: `
4875 --if
4876
4877 100
4878 --ff 100.1
4879
4880 --ssf hello
4881 --ssf
4882
4883 "hello
4884 123
4885 44"
4886 `,
4887 args: []string{"foo"},
4888 expectedInt: 100,
4889 expectedFloat: 100.1,
4890 expectedSlice: []string{"hello", "hello\n 123\n44"},
4891 },
4892 {
4893 name: "end-args",
4894 input: `
4895 --if
4896
4897 100
4898 --
4899 --ff 100.1
4900
4901 --ssf hello
4902 --ssf
4903
4904 hell02
4905 `,
4906 args: []string{"foo"},
4907 expectedInt: 100,
4908 expectedFloat: 0,
4909 expectedSlice: []string{},
4910 },
4911 {
4912 name: "invalid string",
4913 input: `
4914 "
4915 `,
4916 args: []string{"foo"},
4917 expectedInt: 0,
4918 expectedFloat: 0,
4919 expectedSlice: []string{},
4920 },
4921 {
4922 name: "invalid string2",
4923 input: `
4924 --if
4925 "
4926 `,
4927 args: []string{"foo"},
4928 expectError: true,
4929 },
4930 {
4931 name: "incomplete string",
4932 input: `
4933 --ssf
4934 "
4935 hello
4936 `,
4937 args: []string{"foo"},
4938 expectedSlice: []string{"hello"},
4939 },
4940 }
4941
4942 for _, tst := range tests {
4943 t.Run(tst.name, func(t *testing.T) {
4944 r := require.New(t)
4945
4946 fp, err := os.CreateTemp("", "readargs")
4947 r.NoError(err)
4948 _, err = fp.Write([]byte(tst.input))
4949 r.NoError(err)
4950 fp.Close()
4951
4952 cmd := buildMinimalTestCommand()
4953 cmd.ReadArgsFromStdin = true
4954 cmd.Reader, err = os.Open(fp.Name())
4955 r.NoError(err)
4956 cmd.Flags = []Flag{
4957 &Int64Flag{
4958 Name: "if",
4959 },
4960 &FloatFlag{
4961 Name: "ff",
4962 },
4963 &StringSliceFlag{
4964 Name: "ssf",
4965 Config: StringConfig{
4966 TrimSpace: true,
4967 },
4968 },
4969 }
4970
4971 actionCalled := false
4972 cmd.Action = func(ctx context.Context, c *Command) error {
4973 r.Equal(tst.expectedInt, c.Int64("if"))
4974 r.Equal(tst.expectedFloat, c.Float("ff"))
4975 r.Equal(tst.expectedSlice, c.StringSlice("ssf"))
4976 actionCalled = true
4977 return nil
4978 }
4979
4980 err = cmd.Run(context.Background(), tst.args)
4981 if !tst.expectError {
4982 r.NoError(err)
4983 r.True(actionCalled)
4984 } else {
4985 r.Error(err)
4986 }
4987 })
4988 }
4989 }
4990
4991 func TestZeroValueCommand(t *testing.T) {
4992 var cmd Command
4993 assert.NoError(t, cmd.Run(context.Background(), []string{"foo"}))
4994 }
4995
4996 func TestCommandInvalidName(t *testing.T) {
4997 var cmd Command
4998 assert.Equal(t, int64(0), cmd.Int64("foo"))
4999 assert.Equal(t, uint64(0), cmd.Uint64("foo"))
5000 assert.Equal(t, float64(0), cmd.Float("foo"))
5001 assert.Equal(t, "", cmd.String("foo"))
5002 assert.Equal(t, time.Time{}, cmd.Timestamp("foo"))
5003 assert.Equal(t, time.Duration(0), cmd.Duration("foo"))
5004
5005 assert.Equal(t, []int64(nil), cmd.Int64Slice("foo"))
5006 assert.Equal(t, []uint64(nil), cmd.Uint64Slice("foo"))
5007 assert.Equal(t, []float64(nil), cmd.FloatSlice("foo"))
5008 assert.Equal(t, []string(nil), cmd.StringSlice("foo"))
5009 }
5010
5011 func TestCommandCategories(t *testing.T) {
5012 var cc commandCategories = []*commandCategory{
5013 {
5014 name: "foo",
5015 commands: []*Command{},
5016 },
5017 {
5018 name: "bar",
5019 commands: []*Command{},
5020 },
5021 {
5022 name: "goo",
5023 commands: nil,
5024 },
5025 }
5026
5027 sort.Sort(&cc)
5028
5029 var prev *commandCategory
5030 for _, c := range cc {
5031 if prev != nil {
5032 assert.LessOrEqual(t, prev.name, c.name)
5033 }
5034 prev = c
5035 assert.Equal(t, []*Command(nil), c.VisibleCommands())
5036 }
5037 }
5038
5039 func TestCommandSliceFlagSeparator(t *testing.T) {
5040 cmd := &Command{
5041 SliceFlagSeparator: ";",
5042 Flags: []Flag{
5043 &StringSliceFlag{
5044 Name: "foo",
5045 },
5046 },
5047 }
5048
5049 r := require.New(t)
5050 r.NoError(cmd.Run(buildTestContext(t), []string{"app", "--foo", "ff;dd;gg", "--foo", "t,u"}))
5051 r.Equal([]string{"ff", "dd", "gg", "t,u"}, cmd.Value("foo"))
5052 }
5053
5054 func TestCommandSliceFlagSeparatorFromEnvVar(t *testing.T) {
5055 t.Setenv("APP_FOO", "0 1 2")
5056
5057 cmd := &Command{
5058 SliceFlagSeparator: " ",
5059 Flags: []Flag{
5060 &StringSliceFlag{
5061 Name: "foo",
5062 Sources: EnvVars("APP_FOO"),
5063 },
5064 },
5065 }
5066
5067 r := require.New(t)
5068 r.NoError(cmd.Run(buildTestContext(t), []string{"app"}))
5069 r.Equal([]string{"0", "1", "2"}, cmd.Value("foo"))
5070 }
5071
5072 func TestCommandMapKeyValueFlagSeparator(t *testing.T) {
5073 cmd := &Command{
5074 MapFlagKeyValueSeparator: ":",
5075 Flags: []Flag{
5076 &StringMapFlag{
5077 Name: "f_string_map",
5078 },
5079 },
5080 }
5081
5082 r := require.New(t)
5083 r.NoError(cmd.Run(buildTestContext(t), []string{"app", "--f_string_map", "s1:s2,s3:", "--f_string_map", "s4:s5"}))
5084 exp := map[string]string{
5085 "s1": "s2",
5086 "s3": "",
5087 "s4": "s5",
5088 }
5089 r.Equal(exp, cmd.Value("f_string_map"))
5090 }
5091
5092 // TestStringFlagTerminator tests the string flag "--flag" with "--" terminator.
5093 func TestStringFlagTerminator(t *testing.T) {
5094 tests := []struct {
5095 name string
5096 input []string
5097 expectFlag string
5098 expectArgs []string
5099 expectErr bool
5100 errorContain string
5101 }{
5102 {
5103 name: "flag and args after terminator",
5104 input: []string{"test", "--flag", "x", "--", "test", "a1", "a2", "a3"},
5105 expectFlag: "x",
5106 expectArgs: []string{"test", "a1", "a2", "a3"},
5107 },
5108 /* {
5109 name: "missing flag value due to terminator",
5110 input: []string{"test", "--flag", "--", "x"},
5111 expectErr: true,
5112 errorContain: "flag needs an argument",
5113 },*/
5114 {
5115 name: "terminator with no trailing args",
5116 input: []string{"test", "--flag", "x", "--"},
5117 expectFlag: "x",
5118 expectArgs: []string{},
5119 },
5120 {
5121 name: "no terminator, only flag",
5122 input: []string{"test", "--flag", "x"},
5123 expectFlag: "x",
5124 expectArgs: []string{},
5125 },
5126 {
5127 name: "flag defined after --",
5128 input: []string{"test", "--", "x", "--flag=value"},
5129 expectFlag: "",
5130 expectArgs: []string{"x", "--flag=value"},
5131 },
5132 {
5133 name: "flag and without --",
5134 input: []string{"test", "--flag", "value", "x"},
5135 expectFlag: "value",
5136 expectArgs: []string{"x"},
5137 },
5138 }
5139
5140 for _, tc := range tests {
5141 t.Run(tc.name, func(t *testing.T) {
5142 var flagVal string
5143 var argsVal []string
5144
5145 // build minimal command with a StringFlag "flag"
5146 cmd := &Command{
5147 Name: "test",
5148 Flags: []Flag{
5149 &StringFlag{
5150 Name: "flag",
5151 Usage: "a string flag",
5152 Destination: &flagVal,
5153 },
5154 },
5155 Action: func(ctx context.Context, c *Command) error {
5156 argsVal = c.Args().Slice()
5157 return nil
5158 },
5159 }
5160
5161 err := cmd.Run(context.Background(), tc.input)
5162 if tc.expectErr {
5163 assert.Error(t, err)
5164 if err != nil {
5165 assert.Contains(t, strings.ToLower(err.Error()), strings.ToLower(tc.errorContain))
5166 }
5167 } else {
5168 assert.NoError(t, err)
5169 assert.Equal(t, tc.expectFlag, flagVal)
5170 assert.Equal(t, tc.expectArgs, argsVal)
5171 }
5172 })
5173 }
5174 }
5175
5176 // TestBoolFlagTerminator tests the bool flag
5177 func TestBoolFlagTerminator(t *testing.T) {
5178 tests := []struct {
5179 name string
5180 input []string
5181 expectFlag bool
5182 expectArgs []string
5183 expectErr bool
5184 errorContain string
5185 }{
5186 /*{
5187 name: "bool flag with invalid non-bool value",
5188 input: []string{"test", "--flag", "x", "--", "test", "a1", "a2", "a3"},
5189 expectErr: true,
5190 errorContain: "invalid syntax",
5191 },*/
5192 {
5193 name: "bool flag omitted value defaults to true",
5194 input: []string{"test", "--flag", "--", "x"},
5195 expectFlag: true,
5196 expectArgs: []string{"x"},
5197 },
5198 {
5199 name: "bool flag explicitly set to false",
5200 input: []string{"test", "--flag=false", "--", "x"},
5201 expectFlag: false,
5202 expectArgs: []string{"x"},
5203 },
5204 {
5205 name: "bool flag defined after --",
5206 input: []string{"test", "--", "x", "--flag=true"},
5207 expectFlag: false,
5208 expectArgs: []string{"x", "--flag=true"},
5209 },
5210 {
5211 name: "bool flag and without --",
5212 input: []string{"test", "--flag=true", "x"},
5213 expectFlag: true,
5214 expectArgs: []string{"x"},
5215 },
5216 }
5217
5218 for _, tc := range tests {
5219 t.Run(tc.name, func(t *testing.T) {
5220 var flagVal bool
5221 var argsVal []string
5222
5223 // build minimal command with a BoolFlag "flag"
5224 cmd := &Command{
5225 Name: "test",
5226 Flags: []Flag{
5227 &BoolFlag{
5228 Name: "flag",
5229 Usage: "a bool flag",
5230 Destination: &flagVal,
5231 },
5232 },
5233 Action: func(ctx context.Context, c *Command) error {
5234 argsVal = c.Args().Slice()
5235 return nil
5236 },
5237 }
5238
5239 err := cmd.Run(context.Background(), tc.input)
5240 if tc.expectErr {
5241 assert.Error(t, err)
5242 if err != nil {
5243 assert.Contains(t, strings.ToLower(err.Error()), strings.ToLower(tc.errorContain))
5244 }
5245 } else {
5246 assert.NoError(t, err)
5247 assert.Equal(t, tc.expectFlag, flagVal)
5248 assert.Equal(t, tc.expectArgs, argsVal)
5249 }
5250 })
5251 }
5252 }
5253
5254 // TestSliceStringFlagParsing tests the StringSliceFlag
5255 func TestSliceStringFlagParsing(t *testing.T) {
5256 var sliceVal []string
5257
5258 cmdNoDelimiter := &Command{
5259 Name: "test",
5260 Flags: []Flag{
5261 &StringSliceFlag{
5262 Name: "flag",
5263 Usage: "a string slice flag without delimiter",
5264 },
5265 },
5266 Action: func(ctx context.Context, c *Command) error {
5267 sliceVal = c.StringSlice("flag")
5268 return nil
5269 },
5270 }
5271
5272 /*cmdWithDelimiter := &Command{
5273 Name: "test",
5274 Flags: []Flag{
5275 &StringSliceFlag{
5276 Name: "flag",
5277 Usage: "a string slice flag with delimiter",
5278 Delimiter: ':',
5279 },
5280 },
5281 Action: func(ctx context.Context, c *Command) error {
5282 sliceVal = c.StringSlice("flag")
5283 return nil
5284 },
5285 }*/
5286
5287 tests := []struct {
5288 name string
5289 cmd *Command
5290 input []string
5291 expectSlice []string
5292 expectErr bool
5293 errorContain string
5294 }{
5295 {
5296 name: "single value without delimiter (no split)",
5297 cmd: cmdNoDelimiter,
5298 input: []string{"test", "--flag", "x"},
5299 expectSlice: []string{"x"},
5300 },
5301 {
5302 name: "multiple values with comma (default split)",
5303 cmd: cmdNoDelimiter,
5304 input: []string{"test", "--flag", "x,y"},
5305 expectSlice: []string{"x", "y"},
5306 },
5307 /*{
5308 name: "Case 10: with delimiter specified ':'",
5309 cmd: cmdWithDelimiter,
5310 input: []string{"test", "--flag", "x:y"},
5311 expectSlice: []string{"x", "y"},
5312 },*/
5313 {
5314 name: "without delimiter specified, value remains unsplit",
5315 cmd: cmdNoDelimiter,
5316 input: []string{"test", "--flag", "x:y"},
5317 expectSlice: []string{"x:y"},
5318 },
5319 }
5320
5321 for _, tc := range tests {
5322 // Reset sliceVal
5323 sliceVal = nil
5324
5325 t.Run(tc.name, func(t *testing.T) {
5326 err := tc.cmd.Run(context.Background(), tc.input)
5327 if tc.expectErr {
5328 assert.Error(t, err)
5329 if err != nil {
5330 assert.Contains(t, strings.ToLower(err.Error()), strings.ToLower(tc.errorContain))
5331 }
5332 } else {
5333 assert.NoError(t, err)
5334 assert.Equal(t, tc.expectSlice, sliceVal)
5335 }
5336 })
5337 }
5338 }
5339
5340 func TestJSONExportCommand(t *testing.T) {
5341 cmd := buildExtendedTestCommand()
5342 cmd.Arguments = []Argument{
5343 &IntArgs{
5344 Name: "fooi",
5345 },
5346 }
5347
5348 out, err := json.Marshal(cmd)
5349 require.NoError(t, err)
5350
5351 expected := `{
5352 "name": "greet",
5353 "aliases": null,
5354 "usage": "Some app",
5355 "usageText": "app [first_arg] [second_arg]",
5356 "argsUsage": "",
5357 "version": "",
5358 "description": "Description of the application.",
5359 "defaultCommand": "",
5360 "category": "",
5361 "commands": [
5362 {
5363 "name": "config",
5364 "aliases": [
5365 "c"
5366 ],
5367 "usage": "another usage test",
5368 "usageText": "",
5369 "argsUsage": "",
5370 "version": "",
5371 "description": "",
5372 "defaultCommand": "",
5373 "category": "",
5374 "commands": [
5375 {
5376 "name": "sub-config",
5377 "aliases": [
5378 "s",
5379 "ss"
5380 ],
5381 "usage": "another usage test",
5382 "usageText": "",
5383 "argsUsage": "",
5384 "version": "",
5385 "description": "",
5386 "defaultCommand": "",
5387 "category": "",
5388 "commands": null,
5389 "flags": [
5390 {
5391 "name": "sub-flag",
5392 "category": "",
5393 "defaultText": "",
5394 "usage": "",
5395 "required": false,
5396 "hidden": false,
5397 "hideDefault": false,
5398 "local": false,
5399 "defaultValue": "",
5400 "aliases": [
5401 "sub-fl",
5402 "s"
5403 ],
5404 "takesFileArg": false,
5405 "config": {
5406 "TrimSpace": false
5407 },
5408 "onlyOnce": false,
5409 "validateDefaults" : false
5410 },
5411 {
5412 "name": "sub-command-flag",
5413 "category": "",
5414 "defaultText": "",
5415 "usage": "some usage text",
5416 "required": false,
5417 "hidden": false,
5418 "hideDefault": false,
5419 "local": false,
5420 "defaultValue": false,
5421 "aliases": [
5422 "s"
5423 ],
5424 "takesFileArg": false,
5425 "config": {
5426 "Count": null
5427 },
5428 "onlyOnce": false,
5429 "validateDefaults" : false
5430 }
5431 ],
5432 "hideHelp": false,
5433 "hideHelpCommand": false,
5434 "hideVersion": false,
5435 "hidden": false,
5436 "authors": null,
5437 "copyright": "",
5438 "metadata": null,
5439 "sliceFlagSeparator": "",
5440 "disableSliceFlagSeparator": false,
5441 "mapFlagKeyValueSeparator": "",
5442 "useShortOptionHandling": false,
5443 "suggest": false,
5444 "allowExtFlags": false,
5445 "skipFlagParsing": false,
5446 "prefixMatchCommands": false,
5447 "mutuallyExclusiveFlags": null,
5448 "arguments": null,
5449 "readArgsFromStdin": false,
5450 "stopOnNthArg": null
5451 }
5452 ],
5453 "flags": [
5454 {
5455 "name": "flag",
5456 "category": "",
5457 "defaultText": "",
5458 "usage": "",
5459 "required": false,
5460 "hidden": false,
5461 "hideDefault": false,
5462 "local": false,
5463 "defaultValue": "",
5464 "aliases": [
5465 "fl",
5466 "f"
5467 ],
5468 "takesFileArg": true,
5469 "config": {
5470 "TrimSpace": false
5471 },
5472 "onlyOnce": false,
5473 "validateDefaults" : false
5474 },
5475 {
5476 "name": "another-flag",
5477 "category": "",
5478 "defaultText": "",
5479 "usage": "another usage text",
5480 "required": false,
5481 "hidden": false,
5482 "hideDefault": false,
5483 "local": false,
5484 "defaultValue": false,
5485 "aliases": [
5486 "b"
5487 ],
5488 "takesFileArg": false,
5489 "config": {
5490 "Count": null
5491 },
5492 "onlyOnce": false,
5493 "validateDefaults" : false
5494 }
5495 ],
5496 "hideHelp": false,
5497 "hideHelpCommand": false,
5498 "hideVersion": false,
5499 "hidden": false,
5500 "authors": null,
5501 "copyright": "",
5502 "metadata": null,
5503 "sliceFlagSeparator": "",
5504 "disableSliceFlagSeparator": false,
5505 "mapFlagKeyValueSeparator": "",
5506 "useShortOptionHandling": false,
5507 "suggest": false,
5508 "allowExtFlags": false,
5509 "skipFlagParsing": false,
5510 "prefixMatchCommands": false,
5511 "mutuallyExclusiveFlags": null,
5512 "arguments": null,
5513 "readArgsFromStdin": false,
5514 "stopOnNthArg": null
5515 },
5516 {
5517 "name": "info",
5518 "aliases": [
5519 "i",
5520 "in"
5521 ],
5522 "usage": "retrieve generic information",
5523 "usageText": "",
5524 "argsUsage": "",
5525 "version": "",
5526 "description": "",
5527 "defaultCommand": "",
5528 "category": "",
5529 "commands": null,
5530 "flags": null,
5531 "hideHelp": false,
5532 "hideHelpCommand": false,
5533 "hideVersion": false,
5534 "hidden": false,
5535 "authors": null,
5536 "copyright": "",
5537 "metadata": null,
5538 "sliceFlagSeparator": "",
5539 "disableSliceFlagSeparator": false,
5540 "mapFlagKeyValueSeparator": "",
5541 "useShortOptionHandling": false,
5542 "suggest": false,
5543 "allowExtFlags": false,
5544 "skipFlagParsing": false,
5545 "prefixMatchCommands": false,
5546 "mutuallyExclusiveFlags": null,
5547 "arguments": null,
5548 "readArgsFromStdin": false,
5549 "stopOnNthArg": null
5550 },
5551 {
5552 "name": "some-command",
5553 "aliases": null,
5554 "usage": "",
5555 "usageText": "",
5556 "argsUsage": "",
5557 "version": "",
5558 "description": "",
5559 "defaultCommand": "",
5560 "category": "",
5561 "commands": null,
5562 "flags": null,
5563 "hideHelp": false,
5564 "hideHelpCommand": false,
5565 "hideVersion": false,
5566 "hidden": false,
5567 "authors": null,
5568 "copyright": "",
5569 "metadata": null,
5570 "sliceFlagSeparator": "",
5571 "disableSliceFlagSeparator": false,
5572 "mapFlagKeyValueSeparator": "",
5573 "useShortOptionHandling": false,
5574 "suggest": false,
5575 "allowExtFlags": false,
5576 "skipFlagParsing": false,
5577 "prefixMatchCommands": false,
5578 "mutuallyExclusiveFlags": null,
5579 "arguments": null,
5580 "readArgsFromStdin": false,
5581 "stopOnNthArg": null
5582 },
5583 {
5584 "name": "hidden-command",
5585 "aliases": null,
5586 "usage": "",
5587 "usageText": "",
5588 "argsUsage": "",
5589 "version": "",
5590 "description": "",
5591 "defaultCommand": "",
5592 "category": "",
5593 "commands": null,
5594 "flags": [
5595 {
5596 "name": "completable",
5597 "category": "",
5598 "defaultText": "",
5599 "usage": "",
5600 "required": false,
5601 "hidden": false,
5602 "hideDefault": false,
5603 "local": false,
5604 "defaultValue": false,
5605 "aliases": null,
5606 "takesFileArg": false,
5607 "config": {
5608 "Count": null
5609 },
5610 "onlyOnce": false,
5611 "validateDefaults": false
5612 }
5613 ],
5614 "hideHelp": false,
5615 "hideHelpCommand": false,
5616 "hideVersion": false,
5617 "hidden": true,
5618 "authors": null,
5619 "copyright": "",
5620 "metadata": null,
5621 "sliceFlagSeparator": "",
5622 "disableSliceFlagSeparator": false,
5623 "mapFlagKeyValueSeparator": "",
5624 "useShortOptionHandling": false,
5625 "suggest": false,
5626 "allowExtFlags": false,
5627 "skipFlagParsing": false,
5628 "prefixMatchCommands": false,
5629 "mutuallyExclusiveFlags": null,
5630 "arguments": null,
5631 "readArgsFromStdin": false,
5632 "stopOnNthArg": null
5633 },
5634 {
5635 "name": "usage",
5636 "aliases": [
5637 "u"
5638 ],
5639 "usage": "standard usage text",
5640 "usageText": "\nUsage for the usage text\n- formatted: Based on the specified ConfigMap and summon secrets.yml\n- list: Inspect the environment for a specific process running on a Pod\n- for_effect: Compare 'namespace' environment with 'local'\n\n` + "```\\nfunc() { ... }\\n```" + `\n\nShould be a part of the same code block\n",
5641 "argsUsage": "",
5642 "version": "",
5643 "description": "",
5644 "defaultCommand": "",
5645 "category": "",
5646 "commands": [
5647 {
5648 "name": "sub-usage",
5649 "aliases": [
5650 "su"
5651 ],
5652 "usage": "standard usage text",
5653 "usageText": "Single line of UsageText",
5654 "argsUsage": "",
5655 "version": "",
5656 "description": "",
5657 "defaultCommand": "",
5658 "category": "",
5659 "commands": null,
5660 "flags": [
5661 {
5662 "name": "sub-command-flag",
5663 "category": "",
5664 "defaultText": "",
5665 "usage": "some usage text",
5666 "required": false,
5667 "hidden": false,
5668 "hideDefault": false,
5669 "local": false,
5670 "defaultValue": false,
5671 "aliases": [
5672 "s"
5673 ],
5674 "takesFileArg": false,
5675 "config": {
5676 "Count": null
5677 },
5678 "onlyOnce": false,
5679 "validateDefaults" : false
5680 }
5681 ],
5682 "hideHelp": false,
5683 "hideHelpCommand": false,
5684 "hideVersion": false,
5685 "hidden": false,
5686 "authors": null,
5687 "copyright": "",
5688 "metadata": null,
5689 "sliceFlagSeparator": "",
5690 "disableSliceFlagSeparator": false,
5691 "mapFlagKeyValueSeparator": "",
5692 "useShortOptionHandling": false,
5693 "suggest": false,
5694 "allowExtFlags": false,
5695 "skipFlagParsing": false,
5696 "prefixMatchCommands": false,
5697 "mutuallyExclusiveFlags": null,
5698 "arguments": null,
5699 "readArgsFromStdin": false,
5700 "stopOnNthArg": null
5701 }
5702 ],
5703 "flags": [
5704 {
5705 "name": "flag",
5706 "category": "",
5707 "defaultText": "",
5708 "usage": "",
5709 "required": false,
5710 "hidden": false,
5711 "hideDefault": false,
5712 "local": false,
5713 "defaultValue": "",
5714 "aliases": [
5715 "fl",
5716 "f"
5717 ],
5718 "takesFileArg": true,
5719 "config": {
5720 "TrimSpace": false
5721 },
5722 "onlyOnce": false,
5723 "validateDefaults" : false
5724 },
5725 {
5726 "name": "another-flag",
5727 "category": "",
5728 "defaultText": "",
5729 "usage": "another usage text",
5730 "required": false,
5731 "hidden": false,
5732 "hideDefault": false,
5733 "local": false,
5734 "defaultValue": false,
5735 "aliases": [
5736 "b"
5737 ],
5738 "takesFileArg": false,
5739 "config": {
5740 "Count": null
5741 },
5742 "onlyOnce": false,
5743 "validateDefaults" : false
5744 }
5745 ],
5746 "hideHelp": false,
5747 "hideHelpCommand": false,
5748 "hideVersion": false,
5749 "hidden": false,
5750 "authors": null,
5751 "copyright": "",
5752 "metadata": null,
5753 "sliceFlagSeparator": "",
5754 "disableSliceFlagSeparator": false,
5755 "mapFlagKeyValueSeparator": "",
5756 "useShortOptionHandling": false,
5757 "suggest": false,
5758 "allowExtFlags": false,
5759 "skipFlagParsing": false,
5760 "prefixMatchCommands": false,
5761 "mutuallyExclusiveFlags": null,
5762 "arguments": null,
5763 "readArgsFromStdin": false,
5764 "stopOnNthArg": null
5765 }
5766 ],
5767 "flags": [
5768 {
5769 "name": "socket",
5770 "category": "",
5771 "defaultText": "",
5772 "usage": "some 'usage' text",
5773 "required": false,
5774 "hidden": false,
5775 "hideDefault": false,
5776 "local": false,
5777 "defaultValue": "value",
5778 "aliases": [
5779 "s"
5780 ],
5781 "takesFileArg": true,
5782 "config": {
5783 "TrimSpace": false
5784 },
5785 "onlyOnce": false,
5786 "validateDefaults" : false
5787 },
5788 {
5789 "name": "flag",
5790 "category": "",
5791 "defaultText": "",
5792 "usage": "",
5793 "required": false,
5794 "hidden": false,
5795 "hideDefault": false,
5796 "local": false,
5797 "defaultValue": "",
5798 "aliases": [
5799 "fl",
5800 "f"
5801 ],
5802 "takesFileArg": false,
5803 "config": {
5804 "TrimSpace": false
5805 },
5806 "onlyOnce": false,
5807 "validateDefaults" : false
5808 },
5809 {
5810 "name": "another-flag",
5811 "category": "",
5812 "defaultText": "",
5813 "usage": "another usage text",
5814 "required": false,
5815 "hidden": false,
5816 "hideDefault": false,
5817 "local": false,
5818 "defaultValue": false,
5819 "aliases": [
5820 "b"
5821 ],
5822 "takesFileArg": false,
5823 "config": {
5824 "Count": null
5825 },
5826 "onlyOnce": false,
5827 "validateDefaults" : false
5828 },
5829 {
5830 "name": "hidden-flag",
5831 "category": "",
5832 "defaultText": "",
5833 "usage": "",
5834 "required": false,
5835 "hidden": true,
5836 "hideDefault": false,
5837 "local": false,
5838 "defaultValue": false,
5839 "aliases": null,
5840 "takesFileArg": false,
5841 "config": {
5842 "Count": null
5843 },
5844 "onlyOnce": false,
5845 "validateDefaults" : false
5846 }
5847 ],
5848 "hideHelp": false,
5849 "hideHelpCommand": false,
5850 "hideVersion": false,
5851 "hidden": false,
5852 "authors": [
5853 "Harrison <[email protected]>",
5854 {
5855 "Name": "Oliver Allen",
5856 "Address": "[email protected]"
5857 }
5858 ],
5859 "copyright": "",
5860 "metadata": null,
5861 "sliceFlagSeparator": "",
5862 "disableSliceFlagSeparator": false,
5863 "mapFlagKeyValueSeparator": "",
5864 "useShortOptionHandling": false,
5865 "suggest": false,
5866 "allowExtFlags": false,
5867 "skipFlagParsing": false,
5868 "prefixMatchCommands": false,
5869 "mutuallyExclusiveFlags": null,
5870 "arguments": [
5871 {
5872 "name": "fooi",
5873 "value": 0,
5874 "usageText": "",
5875 "minTimes": 0,
5876 "maxTimes": 0,
5877 "config": {
5878 "Base": 0
5879 }
5880 }
5881 ],
5882 "readArgsFromStdin": false,
5883 "stopOnNthArg": null
5884 }
5885 `
5886 assert.JSONEq(t, expected, string(out))
5887 }
5888
5889 func TestCommand_ExclusiveFlags(t *testing.T) {
5890 cmd := &Command{
5891 Name: "bar",
5892 MutuallyExclusiveFlags: []MutuallyExclusiveFlags{
5893 {
5894 Flags: [][]Flag{
5895 {
5896 &StringFlag{
5897 Name: "foo1",
5898 },
5899 },
5900 {
5901 &StringFlag{
5902 Name: "foo2",
5903 },
5904 },
5905 },
5906 },
5907 },
5908 }
5909
5910 err := cmd.Run(buildTestContext(t), []string{"bar", "--foo1", "var1", "--foo2", "var2"})
5911
5912 require.Equal(t, "option foo1 cannot be set along with option foo2", err.Error())
5913 }
5914
5915 func TestCommand_ExclusiveFlagsWithOnUsageError(t *testing.T) {
5916 expectedErr := errors.New("my custom error")
5917 cmd := &Command{
5918 Name: "bar",
5919 MutuallyExclusiveFlags: []MutuallyExclusiveFlags{
5920 {
5921 Flags: [][]Flag{
5922 {
5923 &StringFlag{
5924 Name: "foo1",
5925 },
5926 },
5927 {
5928 &StringFlag{
5929 Name: "foo2",
5930 },
5931 },
5932 },
5933 },
5934 },
5935 OnUsageError: func(_ context.Context, _ *Command, _ error, _ bool) error {
5936 return expectedErr
5937 },
5938 }
5939
5940 actualErr := cmd.Run(buildTestContext(t), []string{"bar", "--foo1", "v1", "--foo2", "v2"})
5941
5942 require.ErrorIs(t, actualErr, expectedErr)
5943 }
5944
5945 func TestCommand_ExclusiveFlagsWithAfter(t *testing.T) {
5946 var called bool
5947 cmd := &Command{
5948 Name: "bar",
5949 MutuallyExclusiveFlags: []MutuallyExclusiveFlags{
5950 {
5951 Category: "cat1",
5952 Flags: [][]Flag{
5953 {
5954 &StringFlag{
5955 Name: "foo",
5956 },
5957 },
5958 {
5959 &StringFlag{
5960 Name: "foo2",
5961 },
5962 },
5963 },
5964 },
5965 },
5966 After: func(ctx context.Context, cmd *Command) error {
5967 called = true
5968 return nil
5969 },
5970 }
5971
5972 require.Error(t, cmd.Run(buildTestContext(t), []string{
5973 "bar",
5974 "--foo", "v1",
5975 "--foo2", "v2",
5976 }))
5977 require.True(t, called)
5978 }
5979
5980 func TestCommand_ParallelRun(t *testing.T) {
5981 t.Parallel()
5982
5983 for i := range 10 {
5984 t.Run(fmt.Sprintf("run_%d", i), func(t *testing.T) {
5985 t.Parallel()
5986
5987 defer func() {
5988 if r := recover(); r != nil {
5989 t.Errorf("unexpected panic - '%s'", r)
5990 }
5991 }()
5992
5993 cmd := &Command{
5994 Name: "debug",
5995 Usage: "make an explosive entrance",
5996 Action: func(_ context.Context, cmd *Command) error {
5997 return nil
5998 },
5999 }
6000
6001 if err := cmd.Run(context.Background(), nil); err != nil {
6002 fmt.Printf("%s\n", err)
6003 }
6004 })
6005 }
6006 }
6007
6008 func TestCommand_ExclusiveFlagsPersistent(t *testing.T) {
6009 exclusiveGroup := func(flags ...string) []MutuallyExclusiveFlags {
6010 grp := MutuallyExclusiveFlags{}
6011 for _, name := range flags {
6012 grp.Flags = append(grp.Flags, []Flag{&StringFlag{Name: name}})
6013 }
6014 return []MutuallyExclusiveFlags{grp}
6015 }
6016
6017 noop := func(_ context.Context, _ *Command) error { return nil }
6018
6019 newBaseCmd := func() *Command {
6020 return &Command{
6021 Name: "root",
6022 MutuallyExclusiveFlags: exclusiveGroup("alpha", "beta"),
6023 Commands: []*Command{{Name: "sub", Action: noop}},
6024 }
6025 }
6026
6027 tests := []struct {
6028 name string
6029 setup func() *Command
6030 args []string
6031 wantErr string
6032 }{
6033 {
6034 name: "single flag propagated to subcommand",
6035 setup: newBaseCmd,
6036 args: []string{"root", "sub", "--alpha", "hello"},
6037 },
6038 {
6039 name: "both exclusive flags on subcommand errors",
6040 setup: newBaseCmd,
6041 args: []string{"root", "sub", "--alpha", "hello", "--beta", "world"},
6042 wantErr: "cannot be set along with",
6043 },
6044 {
6045 name: "neither flag set without required is ok",
6046 setup: newBaseCmd,
6047 args: []string{"root", "sub"},
6048 },
6049 {
6050 name: "exclusive flags checked on grandchild",
6051 setup: func() *Command {
6052 cmd := newBaseCmd()
6053 sub := cmd.Commands[0]
6054 sub.Name = "mid"
6055 sub.Action = nil
6056 sub.Commands = []*Command{{Name: "leaf", Action: noop}}
6057 return cmd
6058 },
6059 args: []string{"root", "mid", "leaf", "--alpha", "hello", "--beta", "world"},
6060 wantErr: "cannot be set along with",
6061 },
6062 {
6063 name: "subcommand own group checked alongside parent group",
6064 setup: func() *Command {
6065 cmd := newBaseCmd()
6066 cmd.Commands[0].MutuallyExclusiveFlags = exclusiveGroup("gamma", "delta")
6067 return cmd
6068 },
6069 args: []string{"root", "sub", "--gamma", "hello", "--delta", "world"},
6070 wantErr: "cannot be set along with",
6071 },
6072 {
6073 name: "parent group violation detected when subcommand has own group",
6074 setup: func() *Command {
6075 cmd := newBaseCmd()
6076 cmd.Commands[0].MutuallyExclusiveFlags = exclusiveGroup("gamma", "delta")
6077 return cmd
6078 },
6079 args: []string{"root", "sub", "--alpha", "hello", "--beta", "world"},
6080 wantErr: "cannot be set along with",
6081 },
6082 {
6083 name: "parent and subcommand groups both pass independently",
6084 setup: func() *Command {
6085 cmd := newBaseCmd()
6086 cmd.Commands[0].MutuallyExclusiveFlags = exclusiveGroup("gamma", "delta")
6087 return cmd
6088 },
6089 args: []string{"root", "sub", "--alpha", "hello", "--gamma", "world"},
6090 },
6091 }
6092
6093 for _, tt := range tests {
6094 t.Run(tt.name, func(t *testing.T) {
6095 err := tt.setup().Run(buildTestContext(t), tt.args)
6096 if tt.wantErr != "" {
6097 require.Error(t, err)
6098 assert.Contains(t, err.Error(), tt.wantErr)
6099 } else {
6100 require.NoError(t, err)
6101 }
6102 })
6103 }
6104 }
6105
6106 func TestEmptyPositionalArgs(t *testing.T) {
6107 testCases := []struct {
6108 Name string
6109 Args []string
6110 Expected []string
6111 }{
6112 {
6113 Name: "empty arg between values",
6114 Args: []string{"app", "hello", "", "world"},
6115 Expected: []string{"hello", "", "world"},
6116 },
6117 {
6118 Name: "empty arg at start",
6119 Args: []string{"app", "", "hello"},
6120 Expected: []string{"", "hello"},
6121 },
6122 {
6123 Name: "whitespace-only arg",
6124 Args: []string{"app", "hello", " ", "world"},
6125 Expected: []string{"hello", " ", "world"},
6126 },
6127 }
6128
6129 for _, tc := range testCases {
6130 t.Run(tc.Name, func(t *testing.T) {
6131 var args []string
6132
6133 cmd := &Command{
6134 Action: func(_ context.Context, cmd *Command) error {
6135 args = cmd.Args().Slice()
6136 return nil
6137 },
6138 }
6139
6140 err := cmd.Run(buildTestContext(t), tc.Args)
6141 assert.NoError(t, err)
6142 assert.Equal(t, tc.Expected, args)
6143 })
6144 }
6145 }
6146
6147 // Regression for #2234: an empty positional arg following a flag used to be
6148 // dropped along with every arg after it.
6149 func TestEmptyPositionalArgsAfterFlag(t *testing.T) {
6150 testCases := []struct {
6151 Name string
6152 Args []string
6153 ExpectedArgs []string
6154 ExpectedFlag string
6155 }{
6156 {
6157 Name: "empty arg after equals-form flag",
6158 Args: []string{"app", "-f=something", "", "arg2", "arg3"},
6159 ExpectedArgs: []string{"", "arg2", "arg3"},
6160 ExpectedFlag: "something",
6161 },
6162 {
6163 Name: "empty arg after space-form flag",
6164 Args: []string{"app", "-f", "something", "", "arg2"},
6165 ExpectedArgs: []string{"", "arg2"},
6166 ExpectedFlag: "something",
6167 },
6168 }
6169
6170 for _, tc := range testCases {
6171 t.Run(tc.Name, func(t *testing.T) {
6172 var args []string
6173 var flagVal string
6174
6175 cmd := &Command{
6176 Flags: []Flag{
6177 &StringFlag{Name: "f"},
6178 },
6179 Action: func(_ context.Context, cmd *Command) error {
6180 args = cmd.Args().Slice()
6181 flagVal = cmd.String("f")
6182 return nil
6183 },
6184 }
6185
6186 err := cmd.Run(buildTestContext(t), tc.Args)
6187 assert.NoError(t, err)
6188 assert.Equal(t, tc.ExpectedArgs, args)
6189 assert.Equal(t, tc.ExpectedFlag, flagVal)
6190 })
6191 }
6192 }
6193
6194 func TestFlagEqualsEmptyValue(t *testing.T) {
6195 t.Run("--flag= sets empty string", func(t *testing.T) {
6196 var val string
6197
6198 cmd := &Command{
6199 Flags: []Flag{
6200 &StringFlag{
6201 Name: "name",
6202 Destination: &val,
6203 },
6204 },
6205 }
6206
6207 err := cmd.Run(buildTestContext(t), []string{"app", "--name="})
6208 assert.NoError(t, err)
6209 assert.Equal(t, "", val)
6210 })
6211
6212 t.Run("--flag= does not consume next positional arg", func(t *testing.T) {
6213 var val string
6214 var args []string
6215
6216 cmd := &Command{
6217 Flags: []Flag{
6218 &StringFlag{
6219 Name: "name",
6220 Destination: &val,
6221 },
6222 },
6223 Action: func(_ context.Context, cmd *Command) error {
6224 args = cmd.Args().Slice()
6225 return nil
6226 },
6227 }
6228
6229 err := cmd.Run(buildTestContext(t), []string{"app", "--name=", "positional"})
6230 assert.NoError(t, err)
6231 assert.Equal(t, "", val)
6232 assert.Equal(t, []string{"positional"}, args)
6233 })
6234 }
6235
6236 // TestCommand_NoDefaultCmdArgMatchingFlag tests the argument set
6237 // of a command which has no default command, and has a flag with
6238 // the name of the next argument
6239 func TestCommand_NoDefaultCmdArgMatchingFlag(t *testing.T) {
6240 expectedArgs := stringSliceArgs{v: []string{"flag"}}
6241 var actualArgs Args
6242 cmd := &Command{
6243 Name: "rootCommand",
6244 Flags: []Flag{
6245 &StringFlag{
6246 Name: "flag",
6247 },
6248 },
6249 Commands: []*Command{
6250 {
6251 Name: "subCommand",
6252 },
6253 },
6254 Action: func(ctx context.Context, c *Command) error {
6255 actualArgs = c.Args()
6256 return nil
6257 },
6258 }
6259 // the last element - "flag" - is an argument sharing the same name as the flag
6260 // "flag" of the rootCommand command
6261 err := cmd.Run(buildTestContext(t), []string{"rootCommand", "--flag", "flagvalue", "flag"})
6262 require.NoError(t, err)
6263 require.Equal(t, &expectedArgs, actualArgs)
6264 }
6265
6266 func TestDefaultCommandWithSubcommandFlags(t *testing.T) {
6267 // Regression test for https://github.com/urfave/cli/issues/2249
6268 // When DefaultCommand is set, flags defined on the default subcommand
6269 // should work even when the subcommand name is omitted.
6270 actionExecuted := false
6271 cmd := &Command{
6272 DefaultCommand: "run1",
6273 Commands: []*Command{
6274 {
6275 Name: "run1",
6276 Usage: "run the main application",
6277 Action: func(ctx context.Context, cmd *Command) error {
6278 actionExecuted = true
6279 return nil
6280 },
6281 Flags: []Flag{
6282 &StringFlag{
6283 Name: "foo",
6284 Required: true,
6285 },
6286 },
6287 },
6288 {
6289 Name: "run2",
6290 Action: func(ctx context.Context, cmd *Command) error {
6291 return nil
6292 },
6293 Flags: []Flag{
6294 &StringFlag{
6295 Name: "value",
6296 Required: true,
6297 },
6298 },
6299 },
6300 },
6301 }
6302
6303 // Using flag without subcommand name should route to default command
6304 err := cmd.Run(buildTestContext(t), []string{"c", "--foo", "bar"})
6305 assert.NoError(t, err)
6306 assert.True(t, actionExecuted, "expected run1 action to be executed")
6307 }
6308
6309 func TestDefaultCommandWithShortFlag(t *testing.T) {
6310 // Covers the short-flag splitting path in parseFlags when DefaultCommand is set
6311 actionRun := false
6312 cmd := &Command{
6313 DefaultCommand: "run",
6314 Commands: []*Command{
6315 {
6316 Name: "run",
6317 Usage: "run the app",
6318 Action: func(ctx context.Context, cmd *Command) error {
6319 actionRun = true
6320 if cmd.String("foo") != "baz" {
6321 return fmt.Errorf("expected foo=baz, got %s", cmd.String("foo"))
6322 }
6323 return nil
6324 },
6325 Flags: []Flag{
6326 &StringFlag{
6327 Name: "foo",
6328 Aliases: []string{"f"},
6329 },
6330 },
6331 },
6332 },
6333 }
6334
6335 err := cmd.Run(buildTestContext(t), []string{"c", "-f", "baz"})
6336 assert.NoError(t, err)
6337 assert.True(t, actionRun, "expected run action to be executed")
6338 }
6339
6340 func TestDefaultCommandWithShortFlagHandling(t *testing.T) {
6341 // Covers the shortOptionHandling for-loop path when DefaultCommand is set
6342 actionRun := false
6343 cmd := &Command{
6344 UseShortOptionHandling: true,
6345 DefaultCommand: "run",
6346 Commands: []*Command{
6347 {
6348 Name: "run",
6349 Usage: "run the app",
6350 Action: func(ctx context.Context, cmd *Command) error {
6351 actionRun = true
6352 if cmd.String("foo") != "baz" {
6353 return fmt.Errorf("expected foo=baz, got %s", cmd.String("foo"))
6354 }
6355 return nil
6356 },
6357 Flags: []Flag{
6358 &StringFlag{
6359 Name: "foo",
6360 Aliases: []string{"f"},
6361 },
6362 },
6363 },
6364 },
6365 }
6366 err := cmd.Run(buildTestContext(t), []string{"c", "-f", "baz"})
6367 assert.NoError(t, err)
6368 assert.True(t, actionRun, "expected run action to be executed")
6369 }
6370
6371 func TestCommand_Path(t *testing.T) {
6372 subCmd := &Command{Name: "bar"}
6373 subSubCmd := &Command{Name: "baz"}
6374 subCmd.Commands = []*Command{subSubCmd}
6375
6376 cmd := &Command{
6377 Name: "foo",
6378 Commands: []*Command{subCmd},
6379 }
6380
6381 require.NoError(t, cmd.Run(buildTestContext(t), []string{"foo", "bar", "baz"}))
6382
6383 assert.Equal(t, []string{"foo"}, cmd.Path())
6384 assert.Equal(t, []string{"foo", "bar"}, subCmd.Path())
6385 assert.Equal(t, []string{"foo", "bar", "baz"}, subSubCmd.Path())
6386 }
6387
6388 func TestCommand_Walk(t *testing.T) {
6389 subCmd := &Command{Name: "bar"}
6390 subSubCmd := &Command{Name: "baz"}
6391 subCmd.Commands = []*Command{subSubCmd}
6392
6393 cmd := &Command{
6394 Name: "foo",
6395 Commands: []*Command{subCmd},
6396 }
6397
6398 var visited []string
6399 err := cmd.Walk(func(c *Command) error {
6400 visited = append(visited, c.Name)
6401 return nil
6402 })
6403 require.NoError(t, err)
6404 assert.Equal(t, []string{"foo", "bar", "baz"}, visited)
6405 }
6406
6407 func TestCommand_Walk_ShortCircuit(t *testing.T) {
6408 subCmd := &Command{Name: "bar"}
6409 subSubCmd := &Command{Name: "baz"}
6410 subCmd.Commands = []*Command{subSubCmd}
6411
6412 cmd := &Command{
6413 Name: "foo",
6414 Commands: []*Command{subCmd},
6415 }
6416
6417 errWalk := fmt.Errorf("stop")
6418 var visited []string
6419 err := cmd.Walk(func(c *Command) error {
6420 visited = append(visited, c.Name)
6421 if c.Name == "bar" {
6422 return errWalk
6423 }
6424 return nil
6425 })
6426 assert.ErrorIs(t, err, errWalk)
6427 assert.Equal(t, []string{"foo", "bar"}, visited)
6428 }
6429
6430 func TestCommand_Walk_Hidden(t *testing.T) {
6431 subCmd := &Command{Name: "bar", HideHelp: true}
6432 subSubCmd := &Command{Name: "baz"}
6433 subCmd.Commands = []*Command{subSubCmd}
6434
6435 cmd := &Command{
6436 Name: "foo",
6437 Commands: []*Command{subCmd},
6438 }
6439
6440 var visited []string
6441 err := cmd.Walk(func(c *Command) error {
6442 visited = append(visited, c.Name)
6443 return nil
6444 })
6445 require.NoError(t, err)
6446 assert.Equal(t, []string{"foo", "bar", "baz"}, visited)
6447 }
6448
6449 func TestCommand_Walk_NilFn(t *testing.T) {
6450 cmd := &Command{Name: "foo"}
6451 assert.Nil(t, cmd.Walk(nil))
6452 }