forked from urfave/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app_test.go
2255 lines (1956 loc) · 49.4 KB
/
app_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package cli
import (
"bytes"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"reflect"
"strings"
"testing"
)
var (
lastExitCode = 0
fakeOsExiter = func(rc int) {
lastExitCode = rc
}
fakeErrWriter = &bytes.Buffer{}
)
func init() {
OsExiter = fakeOsExiter
ErrWriter = fakeErrWriter
}
type opCounts struct {
Total, ShellComplete, OnUsageError, Before, CommandNotFound, Action, After, SubCommand int
}
func ExampleApp_Run() {
// set args for examples sake
os.Args = []string{"greet", "--name", "Jeremy"}
app := &App{
Name: "greet",
Flags: []Flag{
&StringFlag{Name: "name", Value: "bob", Usage: "a name to say"},
},
Action: func(c *Context) error {
fmt.Printf("Hello %v\n", c.String("name"))
return nil
},
UsageText: "app [first_arg] [second_arg]",
Authors: []*Author{{Name: "Oliver Allen", Email: "[email protected]"}},
}
app.Run(os.Args)
// Output:
// Hello Jeremy
}
func ExampleApp_Run_subcommand() {
// set args for examples sake
os.Args = []string{"say", "hi", "english", "--name", "Jeremy"}
app := &App{
Name: "say",
Commands: []*Command{
{
Name: "hello",
Aliases: []string{"hi"},
Usage: "use it to see a description",
Description: "This is how we describe hello the function",
Subcommands: []*Command{
{
Name: "english",
Aliases: []string{"en"},
Usage: "sends a greeting in english",
Description: "greets someone in english",
Flags: []Flag{
&StringFlag{
Name: "name",
Value: "Bob",
Usage: "Name of the person to greet",
},
},
Action: func(c *Context) error {
fmt.Println("Hello,", c.String("name"))
return nil
},
},
},
},
},
}
_ = app.Run(os.Args)
// Output:
// Hello, Jeremy
}
func ExampleApp_Run_appHelp() {
// set args for examples sake
os.Args = []string{"greet", "help"}
app := &App{
Name: "greet",
Version: "0.1.0",
Description: "This is how we describe greet the app",
Authors: []*Author{
{Name: "Harrison", Email: "[email protected]"},
{Name: "Oliver Allen", Email: "[email protected]"},
},
Flags: []Flag{
&StringFlag{Name: "name", Value: "bob", Usage: "a name to say"},
},
Commands: []*Command{
{
Name: "describeit",
Aliases: []string{"d"},
Usage: "use it to see a description",
Description: "This is how we describe describeit the function",
Action: func(c *Context) error {
fmt.Printf("i like to describe things")
return nil
},
},
},
}
_ = app.Run(os.Args)
// Output:
// NAME:
// greet - A new cli application
//
// USAGE:
// greet [global options] command [command options] [arguments...]
//
// VERSION:
// 0.1.0
//
// DESCRIPTION:
// This is how we describe greet the app
//
// AUTHORS:
// Harrison <[email protected]>
// Oliver Allen <[email protected]>
//
// COMMANDS:
// describeit, d use it to see a description
// help, h Shows a list of commands or help for one command
//
// GLOBAL OPTIONS:
// --name value a name to say (default: "bob")
// --help, -h show help (default: false)
// --version, -v print the version (default: false)
}
func ExampleApp_Run_commandHelp() {
// set args for examples sake
os.Args = []string{"greet", "h", "describeit"}
app := &App{
Name: "greet",
Flags: []Flag{
&StringFlag{Name: "name", Value: "bob", Usage: "a name to say"},
},
Commands: []*Command{
{
Name: "describeit",
Aliases: []string{"d"},
Usage: "use it to see a description",
Description: "This is how we describe describeit the function",
Action: func(c *Context) error {
fmt.Printf("i like to describe things")
return nil
},
},
},
}
_ = app.Run(os.Args)
// Output:
// NAME:
// greet describeit - use it to see a description
//
// USAGE:
// greet describeit [arguments...]
//
// DESCRIPTION:
// This is how we describe describeit the function
}
func ExampleApp_Run_noAction() {
app := App{}
app.Name = "greet"
_ = app.Run([]string{"greet"})
// Output:
// NAME:
// greet - A new cli application
//
// USAGE:
// greet [global options] command [command options] [arguments...]
//
// COMMANDS:
// help, h Shows a list of commands or help for one command
//
// GLOBAL OPTIONS:
// --help, -h show help (default: false)
}
func ExampleApp_Run_subcommandNoAction() {
app := &App{
Name: "greet",
Commands: []*Command{
{
Name: "describeit",
Aliases: []string{"d"},
Usage: "use it to see a description",
Description: "This is how we describe describeit the function",
},
},
}
_ = app.Run([]string{"greet", "describeit"})
// Output:
// NAME:
// greet describeit - use it to see a description
//
// USAGE:
// greet describeit [command options] [arguments...]
//
// DESCRIPTION:
// This is how we describe describeit the function
//
// OPTIONS:
// --help, -h show help (default: false)
}
func ExampleApp_Run_bashComplete_withShortFlag() {
os.Args = []string{"greet", "-", "--generate-bash-completion"}
app := NewApp()
app.Name = "greet"
app.EnableBashCompletion = true
app.Flags = []Flag{
&IntFlag{
Name: "other",
Aliases: []string{"o"},
},
&StringFlag{
Name: "xyz",
Aliases: []string{"x"},
},
}
_ = app.Run(os.Args)
// Output:
// --other
// -o
// --xyz
// -x
// --help
// -h
}
func ExampleApp_Run_bashComplete_withLongFlag() {
os.Args = []string{"greet", "--s", "--generate-bash-completion"}
app := NewApp()
app.Name = "greet"
app.EnableBashCompletion = true
app.Flags = []Flag{
&IntFlag{
Name: "other",
Aliases: []string{"o"},
},
&StringFlag{
Name: "xyz",
Aliases: []string{"x"},
},
&StringFlag{
Name: "some-flag,s",
},
&StringFlag{
Name: "similar-flag",
},
}
_ = app.Run(os.Args)
// Output:
// --some-flag
// --similar-flag
}
func ExampleApp_Run_bashComplete_withMultipleLongFlag() {
os.Args = []string{"greet", "--st", "--generate-bash-completion"}
app := NewApp()
app.Name = "greet"
app.EnableBashCompletion = true
app.Flags = []Flag{
&IntFlag{
Name: "int-flag",
Aliases: []string{"i"},
},
&StringFlag{
Name: "string",
Aliases: []string{"s"},
},
&StringFlag{
Name: "string-flag-2",
},
&StringFlag{
Name: "similar-flag",
},
&StringFlag{
Name: "some-flag",
},
}
_ = app.Run(os.Args)
// Output:
// --string
// --string-flag-2
}
func ExampleApp_Run_bashComplete() {
// set args for examples sake
os.Args = []string{"greet", "--generate-bash-completion"}
app := &App{
Name: "greet",
EnableBashCompletion: true,
Commands: []*Command{
{
Name: "describeit",
Aliases: []string{"d"},
Usage: "use it to see a description",
Description: "This is how we describe describeit the function",
Action: func(c *Context) error {
fmt.Printf("i like to describe things")
return nil
},
}, {
Name: "next",
Usage: "next example",
Description: "more stuff to see when generating shell completion",
Action: func(c *Context) error {
fmt.Printf("the next example")
return nil
},
},
},
}
_ = app.Run(os.Args)
// Output:
// describeit
// d
// next
// help
// h
}
func ExampleApp_Run_zshComplete() {
// set args for examples sake
os.Args = []string{"greet", "--generate-bash-completion"}
_ = os.Setenv("_CLI_ZSH_AUTOCOMPLETE_HACK", "1")
app := NewApp()
app.Name = "greet"
app.EnableBashCompletion = true
app.Commands = []*Command{
{
Name: "describeit",
Aliases: []string{"d"},
Usage: "use it to see a description",
Description: "This is how we describe describeit the function",
Action: func(c *Context) error {
fmt.Printf("i like to describe things")
return nil
},
}, {
Name: "next",
Usage: "next example",
Description: "more stuff to see when generating bash completion",
Action: func(c *Context) error {
fmt.Printf("the next example")
return nil
},
},
}
_ = app.Run(os.Args)
// Output:
// describeit:use it to see a description
// d:use it to see a description
// next:next example
// help:Shows a list of commands or help for one command
// h:Shows a list of commands or help for one command
}
func TestApp_Run(t *testing.T) {
s := ""
app := &App{
Action: func(c *Context) error {
s = s + c.Args().First()
return nil
},
}
err := app.Run([]string{"command", "foo"})
expect(t, err, nil)
err = app.Run([]string{"command", "bar"})
expect(t, err, nil)
expect(t, s, "foobar")
}
var commandAppTests = []struct {
name string
expected bool
}{
{"foobar", true},
{"batbaz", true},
{"b", true},
{"f", true},
{"bat", false},
{"nothing", false},
}
func TestApp_Command(t *testing.T) {
app := &App{
Commands: []*Command{
{Name: "foobar", Aliases: []string{"f"}},
{Name: "batbaz", Aliases: []string{"b"}},
},
}
for _, test := range commandAppTests {
expect(t, app.Command(test.name) != nil, test.expected)
}
}
func TestApp_Setup_defaultsReader(t *testing.T) {
app := &App{}
app.Setup()
expect(t, app.Reader, os.Stdin)
}
func TestApp_Setup_defaultsWriter(t *testing.T) {
app := &App{}
app.Setup()
expect(t, app.Writer, os.Stdout)
}
func TestApp_RunAsSubcommandParseFlags(t *testing.T) {
var context *Context
a := &App{
Commands: []*Command{
{
Name: "foo",
Action: func(c *Context) error {
context = c
return nil
},
Flags: []Flag{
&StringFlag{
Name: "lang",
Value: "english",
Usage: "language for the greeting",
},
},
Before: func(_ *Context) error { return nil },
},
},
}
_ = a.Run([]string{"", "foo", "--lang", "spanish", "abcd"})
expect(t, context.Args().Get(0), "abcd")
expect(t, context.String("lang"), "spanish")
}
func TestApp_RunAsSubCommandIncorrectUsage(t *testing.T) {
a := App{
Name: "cmd",
Flags: []Flag{
&StringFlag{Name: "foo"},
},
Writer: bytes.NewBufferString(""),
}
set := flag.NewFlagSet("", flag.ContinueOnError)
_ = set.Parse([]string{"", "-bar"})
c := &Context{flagSet: set}
err := a.RunAsSubcommand(c)
expect(t, err.Error(), "flag provided but not defined: -bar")
}
func TestApp_CommandWithFlagBeforeTerminator(t *testing.T) {
var parsedOption string
var args Args
app := &App{
Commands: []*Command{
{
Name: "cmd",
Flags: []Flag{
&StringFlag{Name: "option", Value: "", Usage: "some option"},
},
Action: func(c *Context) error {
parsedOption = c.String("option")
args = c.Args()
return nil
},
},
},
}
_ = app.Run([]string{"", "cmd", "--option", "my-option", "my-arg", "--", "--notARealFlag"})
expect(t, parsedOption, "my-option")
expect(t, args.Get(0), "my-arg")
expect(t, args.Get(1), "--")
expect(t, args.Get(2), "--notARealFlag")
}
func TestApp_CommandWithDash(t *testing.T) {
var args Args
app := &App{
Commands: []*Command{
{
Name: "cmd",
Action: func(c *Context) error {
args = c.Args()
return nil
},
},
},
}
_ = app.Run([]string{"", "cmd", "my-arg", "-"})
expect(t, args.Get(0), "my-arg")
expect(t, args.Get(1), "-")
}
func TestApp_CommandWithNoFlagBeforeTerminator(t *testing.T) {
var args Args
app := &App{
Commands: []*Command{
{
Name: "cmd",
Action: func(c *Context) error {
args = c.Args()
return nil
},
},
},
}
_ = app.Run([]string{"", "cmd", "my-arg", "--", "notAFlagAtAll"})
expect(t, args.Get(0), "my-arg")
expect(t, args.Get(1), "--")
expect(t, args.Get(2), "notAFlagAtAll")
}
func TestApp_VisibleCommands(t *testing.T) {
app := &App{
Commands: []*Command{
{
Name: "frob",
HelpName: "foo frob",
Action: func(_ *Context) error { return nil },
},
{
Name: "frib",
HelpName: "foo frib",
Hidden: true,
Action: func(_ *Context) error { return nil },
},
},
}
app.Setup()
expected := []*Command{
app.Commands[0],
app.Commands[2], // help
}
actual := app.VisibleCommands()
expect(t, len(expected), len(actual))
for i, actualCommand := range actual {
expectedCommand := expected[i]
if expectedCommand.Action != nil {
// comparing func addresses is OK!
expect(t, fmt.Sprintf("%p", expectedCommand.Action), fmt.Sprintf("%p", actualCommand.Action))
}
func() {
// nil out funcs, as they cannot be compared
// (https://github.com/golang/go/issues/8554)
expectedAction := expectedCommand.Action
actualAction := actualCommand.Action
defer func() {
expectedCommand.Action = expectedAction
actualCommand.Action = actualAction
}()
expectedCommand.Action = nil
actualCommand.Action = nil
if !reflect.DeepEqual(expectedCommand, actualCommand) {
t.Errorf("expected\n%#v\n!=\n%#v", expectedCommand, actualCommand)
}
}()
}
}
func TestApp_UseShortOptionHandling(t *testing.T) {
var one, two bool
var name string
expected := "expectedName"
app := newTestApp()
app.UseShortOptionHandling = true
app.Flags = []Flag{
&BoolFlag{Name: "one", Aliases: []string{"o"}},
&BoolFlag{Name: "two", Aliases: []string{"t"}},
&StringFlag{Name: "name", Aliases: []string{"n"}},
}
app.Action = func(c *Context) error {
one = c.Bool("one")
two = c.Bool("two")
name = c.String("name")
return nil
}
_ = app.Run([]string{"", "-on", expected})
expect(t, one, true)
expect(t, two, false)
expect(t, name, expected)
}
func TestApp_UseShortOptionHandling_missing_value(t *testing.T) {
app := newTestApp()
app.UseShortOptionHandling = true
app.Flags = []Flag{
&StringFlag{Name: "name", Aliases: []string{"n"}},
}
err := app.Run([]string{"", "-n"})
expect(t, err, errors.New("flag needs an argument: -n"))
}
func TestApp_UseShortOptionHandlingCommand(t *testing.T) {
var one, two bool
var name string
expected := "expectedName"
app := newTestApp()
app.UseShortOptionHandling = true
command := &Command{
Name: "cmd",
Flags: []Flag{
&BoolFlag{Name: "one", Aliases: []string{"o"}},
&BoolFlag{Name: "two", Aliases: []string{"t"}},
&StringFlag{Name: "name", Aliases: []string{"n"}},
},
Action: func(c *Context) error {
one = c.Bool("one")
two = c.Bool("two")
name = c.String("name")
return nil
},
}
app.Commands = []*Command{command}
_ = app.Run([]string{"", "cmd", "-on", expected})
expect(t, one, true)
expect(t, two, false)
expect(t, name, expected)
}
func TestApp_UseShortOptionHandlingCommand_missing_value(t *testing.T) {
app := newTestApp()
app.UseShortOptionHandling = true
command := &Command{
Name: "cmd",
Flags: []Flag{
&StringFlag{Name: "name", Aliases: []string{"n"}},
},
}
app.Commands = []*Command{command}
err := app.Run([]string{"", "cmd", "-n"})
expect(t, err, errors.New("flag needs an argument: -n"))
}
func TestApp_UseShortOptionHandlingSubCommand(t *testing.T) {
var one, two bool
var name string
expected := "expectedName"
app := newTestApp()
app.UseShortOptionHandling = true
command := &Command{
Name: "cmd",
}
subCommand := &Command{
Name: "sub",
Flags: []Flag{
&BoolFlag{Name: "one", Aliases: []string{"o"}},
&BoolFlag{Name: "two", Aliases: []string{"t"}},
&StringFlag{Name: "name", Aliases: []string{"n"}},
},
Action: func(c *Context) error {
one = c.Bool("one")
two = c.Bool("two")
name = c.String("name")
return nil
},
}
command.Subcommands = []*Command{subCommand}
app.Commands = []*Command{command}
err := app.Run([]string{"", "cmd", "sub", "-on", expected})
expect(t, err, nil)
expect(t, one, true)
expect(t, two, false)
expect(t, name, expected)
}
func TestApp_UseShortOptionHandlingSubCommand_missing_value(t *testing.T) {
app := newTestApp()
app.UseShortOptionHandling = true
command := &Command{
Name: "cmd",
}
subCommand := &Command{
Name: "sub",
Flags: []Flag{
&StringFlag{Name: "name", Aliases: []string{"n"}},
},
}
command.Subcommands = []*Command{subCommand}
app.Commands = []*Command{command}
err := app.Run([]string{"", "cmd", "sub", "-n"})
expect(t, err, errors.New("flag needs an argument: -n"))
}
func TestApp_Float64Flag(t *testing.T) {
var meters float64
app := &App{
Flags: []Flag{
&Float64Flag{Name: "height", Value: 1.5, Usage: "Set the height, in meters"},
},
Action: func(c *Context) error {
meters = c.Float64("height")
return nil
},
}
_ = app.Run([]string{"", "--height", "1.93"})
expect(t, meters, 1.93)
}
func TestApp_ParseSliceFlags(t *testing.T) {
var parsedIntSlice []int
var parsedStringSlice []string
app := &App{
Commands: []*Command{
{
Name: "cmd",
Flags: []Flag{
&IntSliceFlag{Name: "p", Value: NewIntSlice(), Usage: "set one or more ip addr"},
&StringSliceFlag{Name: "ip", Value: NewStringSlice(), Usage: "set one or more ports to open"},
},
Action: func(c *Context) error {
parsedIntSlice = c.IntSlice("p")
parsedStringSlice = c.StringSlice("ip")
return nil
},
},
},
}
_ = app.Run([]string{"", "cmd", "-p", "22", "-p", "80", "-ip", "8.8.8.8", "-ip", "8.8.4.4"})
IntsEquals := func(a, b []int) bool {
if len(a) != len(b) {
return false
}
for i, v := range a {
if v != b[i] {
return false
}
}
return true
}
StrsEquals := func(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i, v := range a {
if v != b[i] {
return false
}
}
return true
}
var expectedIntSlice = []int{22, 80}
var expectedStringSlice = []string{"8.8.8.8", "8.8.4.4"}
if !IntsEquals(parsedIntSlice, expectedIntSlice) {
t.Errorf("%v does not match %v", parsedIntSlice, expectedIntSlice)
}
if !StrsEquals(parsedStringSlice, expectedStringSlice) {
t.Errorf("%v does not match %v", parsedStringSlice, expectedStringSlice)
}
}
func TestApp_ParseSliceFlagsWithMissingValue(t *testing.T) {
var parsedIntSlice []int
var parsedStringSlice []string
app := &App{
Commands: []*Command{
{
Name: "cmd",
Flags: []Flag{
&IntSliceFlag{Name: "a", Usage: "set numbers"},
&StringSliceFlag{Name: "str", Usage: "set strings"},
},
Action: func(c *Context) error {
parsedIntSlice = c.IntSlice("a")
parsedStringSlice = c.StringSlice("str")
return nil
},
},
},
}
_ = app.Run([]string{"", "cmd", "-a", "2", "-str", "A"})
var expectedIntSlice = []int{2}
var expectedStringSlice = []string{"A"}
if parsedIntSlice[0] != expectedIntSlice[0] {
t.Errorf("%v does not match %v", parsedIntSlice[0], expectedIntSlice[0])
}
if parsedStringSlice[0] != expectedStringSlice[0] {
t.Errorf("%v does not match %v", parsedIntSlice[0], expectedIntSlice[0])
}
}
func TestApp_DefaultStdin(t *testing.T) {
app := &App{}
app.Setup()
if app.Reader != os.Stdin {
t.Error("Default input reader not set.")
}
}
func TestApp_DefaultStdout(t *testing.T) {
app := &App{}
app.Setup()
if app.Writer != os.Stdout {
t.Error("Default output writer not set.")
}
}
func TestApp_SetStdin(t *testing.T) {
buf := make([]byte, 12)
app := &App{
Name: "test",
Reader: strings.NewReader("Hello World!"),
Action: func(c *Context) error {
_, err := c.App.Reader.Read(buf)
return err
},
}
err := app.Run([]string{"help"})
if err != nil {
t.Fatalf("Run error: %s", err)
}
if string(buf) != "Hello World!" {
t.Error("App did not read input from desired reader.")
}
}
func TestApp_SetStdin_Subcommand(t *testing.T) {
buf := make([]byte, 12)
app := &App{
Name: "test",
Reader: strings.NewReader("Hello World!"),
Commands: []*Command{
{
Name: "command",
Subcommands: []*Command{
{
Name: "subcommand",
Action: func(c *Context) error {
_, err := c.App.Reader.Read(buf)
return err
},
},
},
},
},
}
err := app.Run([]string{"test", "command", "subcommand"})
if err != nil {
t.Fatalf("Run error: %s", err)
}
if string(buf) != "Hello World!" {
t.Error("App did not read input from desired reader.")
}
}
func TestApp_SetStdout(t *testing.T) {
var w bytes.Buffer
app := &App{
Name: "test",
Writer: &w,
}
err := app.Run([]string{"help"})
if err != nil {
t.Fatalf("Run error: %s", err)
}
if w.Len() == 0 {
t.Error("App did not write output to desired writer.")
}
}
func TestApp_BeforeFunc(t *testing.T) {
counts := &opCounts{}
beforeError := fmt.Errorf("fail")
var err error
app := &App{
Before: func(c *Context) error {
counts.Total++
counts.Before = counts.Total
s := c.String("opt")
if s == "fail" {
return beforeError
}
return nil
},
Commands: []*Command{
{
Name: "sub",
Action: func(c *Context) error {
counts.Total++
counts.SubCommand = counts.Total
return nil
},
},
},
Flags: []Flag{
&StringFlag{Name: "opt"},
},
Writer: ioutil.Discard,
}
// run with the Before() func succeeding
err = app.Run([]string{"command", "--opt", "succeed", "sub"})
if err != nil {
t.Fatalf("Run error: %s", err)
}
if counts.Before != 1 {
t.Errorf("Before() not executed when expected")
}
if counts.SubCommand != 2 {
t.Errorf("Subcommand not executed when expected")
}
// reset
counts = &opCounts{}