Debian Codegraph @

flag_test.go

raw symbols SCIP
1 package cli
2
3 import (
4 "context"
5 "errors"
6 "flag"
7 "fmt"
8 "os"
9 "reflect"
10 "regexp"
11 "runtime"
12 "sort"
13 "strings"
14 "testing"
15 "time"
16
17 "github.com/stretchr/testify/assert"
18 "github.com/stretchr/testify/require"
19 )
20
21 type Parser [2]string
22
23 func (p *Parser) Set(value string) error {
24 parts := strings.Split(value, ",")
25 if len(parts) != 2 {
26 return fmt.Errorf("invalid format")
27 }
28
29 (*p)[0] = parts[0]
30 (*p)[1] = parts[1]
31
32 return nil
33 }
34
35 func (p *Parser) String() string {
36 return fmt.Sprintf("%s,%s", p[0], p[1])
37 }
38
39 func (p *Parser) Get() any {
40 return p
41 }
42
43 var boolFlagTests = []struct {
44 name string
45 expected string
46 }{
47 {"help", "--help\t"},
48 {"h", "-h\t"},
49 }
50
51 func TestBoolFlagHelpOutput(t *testing.T) {
52 for _, test := range boolFlagTests {
53 fl := &BoolFlag{Name: test.name}
54 output := fl.String()
55 assert.Equal(t, test.expected, output)
56 }
57 }
58
59 func TestBoolFlagApply_SetsAllNames(t *testing.T) {
60 v := false
61 cmd := buildMinimalTestCommand()
62 cmd.Flags = []Flag{
63 &BoolFlag{Name: "wat", Aliases: []string{"W", "huh"}, Destination: &v},
64 }
65
66 err := cmd.Run(buildTestContext(t), []string{"", "--wat", "-W", "--huh"})
67 assert.NoError(t, err)
68 assert.True(t, v)
69 }
70
71 func TestBoolFlagValueFromCommand(t *testing.T) {
72 tf := &BoolFlag{Name: "trueflag"}
73 ff := &BoolFlag{Name: "falseflag"}
74
75 cmd := buildMinimalTestCommand()
76 cmd.Flags = []Flag{
77 tf,
78 ff,
79 }
80
81 r := require.New(t)
82 r.NoError(cmd.Set(tf.Name, "true"))
83 r.NoError(cmd.Set(ff.Name, "false"))
84 r.True(cmd.Bool(tf.Name))
85 r.False(cmd.Bool(ff.Name))
86 }
87
88 func TestBoolFlagApply_SetsCount(t *testing.T) {
89 v := false
90 count := 0
91 cmd := buildMinimalTestCommand()
92 cmd.Flags = []Flag{
93 &BoolFlag{Name: "wat", Aliases: []string{"W", "huh"}, Destination: &v, Config: BoolConfig{Count: &count}},
94 }
95
96 assert.NoError(t, cmd.Run(buildTestContext(t), []string{"", "--wat", "-W", "--huh"}))
97 assert.True(t, v)
98 assert.Equal(t, 3, count)
99 }
100
101 func TestBoolFlagCountFromCommand(t *testing.T) {
102 boolCountTests := []struct {
103 name string
104 input []string
105 expectedVal bool
106 expectedCount int
107 }{
108 {
109 name: "3 count",
110 input: []string{"main", "-tf", "-w", "-huh"},
111 expectedVal: true,
112 expectedCount: 3,
113 },
114 {
115 name: "single count",
116 input: []string{"main", "-huh"},
117 expectedVal: true,
118 expectedCount: 1,
119 },
120 {
121 name: "zero count",
122 input: []string{"main"},
123 expectedVal: false,
124 expectedCount: 0,
125 },
126 }
127
128 flags := func() []Flag {
129 return []Flag{
130 &BoolFlag{Name: "tf", Aliases: []string{"w", "huh"}},
131 &BoolWithInverseFlag{Name: "tf", Aliases: []string{"w", "huh"}},
132 }
133 }
134 for index := range flags() {
135 for _, bct := range boolCountTests {
136 t.Run(bct.name, func(t *testing.T) {
137 bf := flags()[index]
138 cmd := &Command{
139 Flags: []Flag{
140 bf,
141 },
142 }
143 r := require.New(t)
144
145 r.NoError(cmd.Run(buildTestContext(t), bct.input))
146
147 for _, alias := range bf.Names() {
148 r.Equal(bct.expectedCount, cmd.Count(alias))
149 r.Equal(bct.expectedVal, cmd.Value(alias))
150 }
151 })
152 }
153 }
154 }
155
156 func TestFlagsFromEnv(t *testing.T) {
157 testCases := []struct {
158 name string
159 input string
160 output any
161 fl Flag
162 errContains string
163 }{
164 {
165 name: "BoolFlag valid true",
166 input: "1",
167 output: true,
168 fl: &BoolFlag{Name: "debug", Sources: EnvVars("DEBUG")},
169 },
170 {
171 name: "BoolFlag valid false",
172 input: "false",
173 output: false,
174 fl: &BoolFlag{Name: "debug", Sources: EnvVars("DEBUG")},
175 },
176 {
177 name: "BoolFlag invalid",
178 input: "foobar",
179 output: true,
180 fl: &BoolFlag{Name: "debug", Sources: EnvVars("DEBUG")},
181 errContains: `could not parse "foobar" as bool value from environment variable ` +
182 `"DEBUG" for flag debug:`,
183 },
184 {
185 name: "BoolInverse Empty",
186 output: false,
187 fl: &BoolWithInverseFlag{Name: "debug", Sources: EnvVars("DEBUG")},
188 },
189 {
190 name: "DurationFlag valid",
191 input: "1s",
192 output: 1 * time.Second,
193 fl: &DurationFlag{Name: "time", Sources: EnvVars("TIME")},
194 },
195 {
196 name: "DurationFlag invalid",
197 input: "foobar",
198 output: false,
199 fl: &DurationFlag{Name: "time", Sources: EnvVars("TIME")},
200 errContains: `could not parse "foobar" as time.Duration value from environment ` +
201 `variable "TIME" for flag time:`,
202 },
203
204 {
205 name: "Float64Flag valid",
206 input: "1.2",
207 output: 1.2,
208 fl: &FloatFlag{Name: "seconds", Sources: EnvVars("SECONDS")},
209 },
210 {
211 name: "Float64Flag valid from int",
212 input: "1",
213 output: 1.0,
214 fl: &FloatFlag{Name: "seconds", Sources: EnvVars("SECONDS")},
215 },
216 {
217 name: "Float64Flag invalid",
218 input: "foobar",
219 output: 0,
220 fl: &FloatFlag{Name: "seconds", Sources: EnvVars("SECONDS")},
221 errContains: `could not parse "foobar" as float64 value from environment variable ` +
222 `"SECONDS" for flag seconds:`,
223 },
224
225 {
226 name: "Int64Flag valid",
227 input: "1",
228 output: int64(1),
229 fl: &Int64Flag{Name: "seconds", Sources: EnvVars("SECONDS")},
230 },
231 {
232 name: "Int64Flag invalid from float",
233 input: "1.2",
234 output: 0,
235 fl: &Int64Flag{Name: "seconds", Sources: EnvVars("SECONDS")},
236 errContains: `could not parse "1.2" as int64 value from environment variable ` +
237 `"SECONDS" for flag seconds:`,
238 },
239 {
240 name: "Int64Flag invalid",
241 input: "foobar",
242 output: 0,
243 fl: &Int64Flag{Name: "seconds", Sources: EnvVars("SECONDS")},
244 errContains: `could not parse "foobar" as int64 value from environment variable ` +
245 `"SECONDS" for flag seconds:`,
246 },
247 {
248 name: "Int64Flag valid from hex",
249 input: "deadBEEF",
250 output: int64(3735928559),
251 fl: &Int64Flag{Name: "seconds", Sources: EnvVars("SECONDS"), Config: IntegerConfig{Base: 16}},
252 },
253 {
254 name: "Int64Flag invalid from octal",
255 input: "08",
256 output: 0,
257 fl: &Int64Flag{Name: "seconds", Sources: EnvVars("SECONDS"), Config: IntegerConfig{Base: 8}},
258 errContains: `could not parse "08" as int64 value from environment variable ` +
259 `"SECONDS" for flag seconds:`,
260 },
261
262 {
263 name: "Float64SliceFlag valid",
264 input: "1.0,2",
265 output: []float64{1, 2},
266 fl: &FloatSliceFlag{Name: "seconds", Sources: EnvVars("SECONDS")},
267 },
268 {
269 name: "Float64SliceFlag invalid",
270 input: "foobar",
271 output: []float64{},
272 fl: &FloatSliceFlag{Name: "seconds", Sources: EnvVars("SECONDS")},
273 errContains: `could not parse "foobar" as []float64 value from environment ` +
274 `variable "SECONDS" for flag seconds:`,
275 },
276 {
277 name: "Generic",
278 input: "foo,bar",
279 output: &Parser{"foo", "bar"},
280 fl: &GenericFlag{Name: "names", Value: &Parser{}, Sources: EnvVars("NAMES")},
281 },
282 {
283 name: "Int64SliceFlag valid",
284 input: "1,2",
285 output: []int64{1, 2},
286 fl: &Int64SliceFlag{Name: "seconds", Sources: EnvVars("SECONDS")},
287 },
288 {
289 name: "Int64SliceFlag invalid from float",
290 input: "1.2,2",
291 output: []int64{},
292 fl: &Int64SliceFlag{Name: "seconds", Sources: EnvVars("SECONDS")},
293 errContains: `could not parse "1.2,2" as []int64 value from environment variable ` +
294 `"SECONDS" for flag seconds:`,
295 },
296 {
297 name: "Int64SliceFlag invalid",
298 input: "foobar",
299 output: []int64{},
300 fl: &Int64SliceFlag{Name: "seconds", Sources: EnvVars("SECONDS")},
301 errContains: `could not parse "foobar" as []int64 value from environment variable ` +
302 `"SECONDS" for flag seconds:`,
303 },
304
305 {
306 name: "Uint64SliceFlag valid",
307 input: "1,2",
308 output: []uint64{1, 2},
309 fl: &Uint64SliceFlag{Name: "seconds", Sources: EnvVars("SECONDS")},
310 },
311 {
312 name: "Uint64SliceFlag invalid with float",
313 input: "1.2,2",
314 output: []uint64{},
315 fl: &Uint64SliceFlag{Name: "seconds", Sources: EnvVars("SECONDS")},
316 errContains: `could not parse "1.2,2" as []uint64 value from environment variable ` +
317 `"SECONDS" for flag seconds:`,
318 },
319 {
320 name: "Uint64SliceFlag invalid",
321 input: "foobar",
322 output: []uint64{},
323 fl: &Uint64SliceFlag{Name: "seconds", Sources: EnvVars("SECONDS")},
324 errContains: `could not parse "foobar" as []uint64 value from environment variable ` +
325 `"SECONDS" for flag seconds:`,
326 },
327
328 {
329 name: "StringFlag valid",
330 input: "foo",
331 output: "foo",
332 fl: &StringFlag{Name: "name", Sources: EnvVars("NAME")},
333 },
334 {
335 name: "StringFlag valid with TrimSpace",
336 input: " foo",
337 output: "foo",
338 fl: &StringFlag{Name: "names", Sources: EnvVars("NAMES"), Config: StringConfig{TrimSpace: true}},
339 },
340
341 {
342 name: "StringSliceFlag valid",
343 input: "foo,bar",
344 output: []string{"foo", "bar"},
345 fl: &StringSliceFlag{Name: "names", Sources: EnvVars("NAMES")},
346 },
347 {
348 name: "StringSliceFlag valid with TrimSpace",
349 input: "foo , bar ",
350 output: []string{"foo", "bar"},
351 fl: &StringSliceFlag{Name: "names", Sources: EnvVars("NAMES"), Config: StringConfig{TrimSpace: true}},
352 },
353 {
354 name: "StringSliceFlag valid without TrimSpace",
355 input: "foo , bar ",
356 output: []string{"foo ", " bar "},
357 fl: &StringSliceFlag{Name: "names", Sources: EnvVars("NAMES")},
358 },
359
360 {
361 name: "StringMapFlag valid",
362 input: "foo=bar,empty=",
363 output: map[string]string{"foo": "bar", "empty": ""},
364 fl: &StringMapFlag{Name: "names", Sources: EnvVars("NAMES")},
365 },
366 {
367 name: "StringMapFlag valid with TrimSpace",
368 input: "foo= bar ",
369 output: map[string]string{"foo": "bar"},
370 fl: &StringMapFlag{Name: "names", Sources: EnvVars("NAMES"), Config: StringConfig{TrimSpace: true}},
371 },
372
373 {
374 name: "Uint64Flag valid",
375 input: "1",
376 output: uint64(1),
377 fl: &Uint64Flag{Name: "seconds", Sources: EnvVars("SECONDS")},
378 },
379 {
380 name: "Uint64Flag valid leading zero",
381 input: "08",
382 output: uint64(8),
383 fl: &Uint64Flag{Name: "seconds", Sources: EnvVars("SECONDS"), Config: IntegerConfig{Base: 10}},
384 },
385 {
386 name: "Uint64Flag valid from octal",
387 input: "755",
388 output: uint64(493),
389 fl: &Uint64Flag{Name: "seconds", Sources: EnvVars("SECONDS"), Config: IntegerConfig{Base: 8}},
390 },
391 {
392 name: "Uint64Flag valid from hex",
393 input: "deadBEEF",
394 output: uint64(3735928559),
395 fl: &Uint64Flag{Name: "seconds", Sources: EnvVars("SECONDS"), Config: IntegerConfig{Base: 16}},
396 },
397 {
398 name: "Uint64Flag invalid octal",
399 input: "08",
400 output: 0,
401 fl: &Uint64Flag{Name: "seconds", Sources: EnvVars("SECONDS"), Config: IntegerConfig{Base: 8}},
402 errContains: `could not parse "08" as uint64 value from environment variable ` +
403 `"SECONDS" for flag seconds:`,
404 },
405 {
406 name: "Uint64Flag invalid float",
407 input: "1.2",
408 output: 0,
409 fl: &Uint64Flag{Name: "seconds", Sources: EnvVars("SECONDS")},
410 errContains: `could not parse "1.2" as uint64 value from environment variable ` +
411 `"SECONDS" for flag seconds:`,
412 },
413 {
414 name: "Uint64Flag invalid",
415 input: "foobar",
416 output: 0,
417 fl: &Uint64Flag{Name: "seconds", Sources: EnvVars("SECONDS")},
418 errContains: `could not parse "foobar" as uint64 value from environment variable ` +
419 `"SECONDS" for flag seconds:`,
420 },
421 }
422
423 for _, tc := range testCases {
424 t.Run(tc.name, func(t *testing.T) {
425 r := require.New(t)
426
427 r.Implements((*DocGenerationFlag)(nil), tc.fl)
428 f := tc.fl.(DocGenerationFlag)
429
430 envVarSlice := f.GetEnvVars()
431 t.Setenv(envVarSlice[0], tc.input)
432
433 cmd := &Command{
434 Flags: []Flag{tc.fl},
435 Action: func(_ context.Context, cmd *Command) error {
436 r.Equal(tc.output, cmd.Value(tc.fl.Names()[0]))
437 r.True(tc.fl.IsSet())
438 r.Equal(tc.fl.Names(), cmd.FlagNames())
439
440 return nil
441 },
442 }
443
444 err := cmd.Run(buildTestContext(t), []string{"run"})
445
446 if tc.errContains != "" {
447 r.NotNil(err)
448 r.ErrorContains(err, tc.errContains)
449
450 return
451 }
452
453 r.NoError(err)
454 })
455 }
456 }
457
458 type nodocFlag struct {
459 Flag
460
461 Name string
462 }
463
464 func TestFlagStringifying(t *testing.T) {
465 for _, tc := range []struct {
466 name string
467 fl Flag
468 expected string
469 }{
470 {
471 name: "bool-flag",
472 fl: &BoolFlag{Name: "vividly"},
473 expected: "--vividly\t",
474 },
475 {
476 name: "bool-flag-with-default-text",
477 fl: &BoolFlag{Name: "wildly", DefaultText: "scrambled"},
478 expected: "--wildly\t(default: scrambled)",
479 },
480 {
481 name: "bool-inv-flag",
482 fl: &BoolWithInverseFlag{Name: "vividly"},
483 expected: "--vividly, --no-vividly\t(default: false)",
484 },
485 {
486 name: "duration-flag",
487 fl: &DurationFlag{Name: "scream-for"},
488 expected: "--scream-for duration\t(default: 0s)",
489 },
490 {
491 name: "duration-flag-with-default-text",
492 fl: &DurationFlag{Name: "feels-about", DefaultText: "whimsically"},
493 expected: "--feels-about duration\t(default: whimsically)",
494 },
495 {
496 name: "float64-flag",
497 fl: &FloatFlag{Name: "arduous"},
498 expected: "--arduous float\t(default: 0)",
499 },
500 {
501 name: "float64-flag-with-default-text",
502 fl: &FloatFlag{Name: "filibuster", DefaultText: "42"},
503 expected: "--filibuster float\t(default: 42)",
504 },
505 {
506 name: "float64-slice-flag",
507 fl: &FloatSliceFlag{Name: "pizzas"},
508 expected: "--pizzas float [ --pizzas float ]\t",
509 },
510 {
511 name: "float64-slice-flag-with-default-text",
512 fl: &FloatSliceFlag{Name: "pepperonis", DefaultText: "shaved"},
513 expected: "--pepperonis float [ --pepperonis float ]\t(default: shaved)",
514 },
515 {
516 name: "generic-flag",
517 fl: &GenericFlag{Name: "yogurt"},
518 expected: "--yogurt value\t",
519 },
520 {
521 name: "generic-flag-with-default-text",
522 fl: &GenericFlag{Name: "ricotta", DefaultText: "plops"},
523 expected: "--ricotta value\t(default: plops)",
524 },
525 {
526 name: "int-flag",
527 fl: &Int64Flag{Name: "grubs"},
528 expected: "--grubs int\t(default: 0)",
529 },
530 {
531 name: "int-flag-with-default-text",
532 fl: &Int64Flag{Name: "poisons", DefaultText: "11ty"},
533 expected: "--poisons int\t(default: 11ty)",
534 },
535 {
536 name: "int-slice-flag",
537 fl: &Int64SliceFlag{Name: "pencils"},
538 expected: "--pencils int [ --pencils int ]\t",
539 },
540 {
541 name: "int-slice-flag-with-default-text",
542 fl: &Int64Flag{Name: "pens", DefaultText: "-19"},
543 expected: "--pens int\t(default: -19)",
544 },
545 {
546 name: "uint-slice-flag",
547 fl: &Uint64SliceFlag{Name: "pencils"},
548 expected: "--pencils uint [ --pencils uint ]\t",
549 },
550 {
551 name: "uint-slice-flag-with-default-text",
552 fl: &Uint64Flag{Name: "pens", DefaultText: "29"},
553 expected: "--pens uint\t(default: 29)",
554 },
555 {
556 name: "int64-flag",
557 fl: &Int64Flag{Name: "flume"},
558 expected: "--flume int\t(default: 0)",
559 },
560 {
561 name: "int64-flag-with-default-text",
562 fl: &Int64Flag{Name: "shattering", DefaultText: "22"},
563 expected: "--shattering int\t(default: 22)",
564 },
565 {
566 name: "uint64-slice-flag",
567 fl: &Uint64SliceFlag{Name: "drawers"},
568 expected: "--drawers uint [ --drawers uint ]\t",
569 },
570 {
571 name: "uint64-slice-flag-with-default-text",
572 fl: &Uint64SliceFlag{Name: "handles", DefaultText: "-2"},
573 expected: "--handles uint [ --handles uint ]\t(default: -2)",
574 },
575 {
576 name: "string-flag",
577 fl: &StringFlag{Name: "arf-sound"},
578 expected: "--arf-sound string\t",
579 },
580 {
581 name: "string-flag-with-default-text",
582 fl: &StringFlag{Name: "woof-sound", DefaultText: "urp"},
583 expected: "--woof-sound string\t(default: urp)",
584 },
585 {
586 name: "string-slice-flag",
587 fl: &StringSliceFlag{Name: "meow-sounds"},
588 expected: "--meow-sounds string [ --meow-sounds string ]\t",
589 },
590 {
591 name: "string-slice-flag-with-default-text",
592 fl: &StringSliceFlag{Name: "moo-sounds", DefaultText: "awoo"},
593 expected: "--moo-sounds string [ --moo-sounds string ]\t(default: awoo)",
594 },
595 {
596 name: "timestamp-flag",
597 fl: &TimestampFlag{Name: "eating"},
598 expected: "--eating time\t",
599 },
600 {
601 name: "timestamp-flag-with-default-text",
602 fl: &TimestampFlag{Name: "sleeping", DefaultText: "earlier"},
603 expected: "--sleeping time\t(default: earlier)",
604 },
605 {
606 name: "uint-flag",
607 fl: &Uint64Flag{Name: "jars"},
608 expected: "--jars uint\t(default: 0)",
609 },
610 {
611 name: "uint-flag-with-default-text",
612 fl: &Uint64Flag{Name: "bottles", DefaultText: "99"},
613 expected: "--bottles uint\t(default: 99)",
614 },
615 {
616 name: "uint64-flag",
617 fl: &Uint64Flag{Name: "cans"},
618 expected: "--cans uint\t(default: 0)",
619 },
620 {
621 name: "uint64-flag-with-default-text",
622 fl: &Uint64Flag{Name: "tubes", DefaultText: "13"},
623 expected: "--tubes uint\t(default: 13)",
624 },
625 {
626 name: "nodoc-flag",
627 fl: &nodocFlag{Name: "scarecrow"},
628 expected: "",
629 },
630 } {
631 t.Run(tc.name, func(ct *testing.T) {
632 s := stringifyFlag(tc.fl)
633 assert.Equal(t, tc.expected, s, "stringified flag %q does not match expected", s)
634 })
635 }
636 }
637
638 var stringFlagTests = []struct {
639 name string
640 aliases []string
641 usage string
642 value string
643 expected string
644 }{
645 {"foo", nil, "", "", "--foo string\t"},
646 {"f", nil, "", "", "-f string\t"},
647 {"f", nil, "The total `foo` desired", "all", "-f foo\tThe total foo desired (default: \"all\")"},
648 {"test", nil, "", "Something", "--test string\t(default: \"Something\")"},
649 {"config", []string{"c"}, "Load configuration from `FILE`", "", "--config FILE, -c FILE\tLoad configuration from FILE"},
650 {"config", []string{"c"}, "Load configuration from `CONFIG`", "config.json", "--config CONFIG, -c CONFIG\tLoad configuration from CONFIG (default: \"config.json\")"},
651 }
652
653 func TestStringFlagHelpOutput(t *testing.T) {
654 for _, test := range stringFlagTests {
655 fl := &StringFlag{Name: test.name, Aliases: test.aliases, Usage: test.usage, Value: test.value}
656 assert.Equal(t, test.expected, fl.String())
657 }
658 }
659
660 func TestStringFlagDefaultText(t *testing.T) {
661 fl := &StringFlag{Name: "foo", Aliases: nil, Usage: "amount of `foo` requested", Value: "none", DefaultText: "all of it"}
662 expected := "--foo foo\tamount of foo requested (default: all of it)"
663 assert.Equal(t, expected, fl.String())
664 }
665
666 func TestStringFlagWithEnvVarHelpOutput(t *testing.T) {
667 t.Setenv("APP_FOO", "derp")
668
669 for _, test := range stringFlagTests {
670 fl := &StringFlag{Name: test.name, Aliases: test.aliases, Value: test.value, Sources: EnvVars("APP_FOO")}
671 output := fl.String()
672
673 expectedSuffix := withEnvHint([]string{"APP_FOO"}, "")
674 if !strings.HasSuffix(output, expectedSuffix) {
675 t.Errorf("%s does not end with"+expectedSuffix, output)
676 }
677 }
678 }
679
680 var _ = []struct {
681 name string
682 aliases []string
683 usage string
684 value string
685 prefixer FlagNamePrefixFunc
686 expected string
687 }{
688 {name: "foo", usage: "", value: "", prefixer: func(a []string, b string) string {
689 return fmt.Sprintf("name: %s, ph: %s", a, b)
690 }, expected: "name: foo, ph: value\t"},
691 {name: "f", usage: "", value: "", prefixer: func(a []string, b string) string {
692 return fmt.Sprintf("name: %s, ph: %s", a, b)
693 }, expected: "name: f, ph: value\t"},
694 {name: "f", usage: "The total `foo` desired", value: "all", prefixer: func(a []string, b string) string {
695 return fmt.Sprintf("name: %s, ph: %s", a, b)
696 }, expected: "name: f, ph: foo\tThe total foo desired (default: \"all\")"},
697 {name: "test", usage: "", value: "Something", prefixer: func(a []string, b string) string {
698 return fmt.Sprintf("name: %s, ph: %s", a, b)
699 }, expected: "name: test, ph: value\t(default: \"Something\")"},
700 {name: "config", aliases: []string{"c"}, usage: "Load configuration from `FILE`", value: "", prefixer: func(a []string, b string) string {
701 return fmt.Sprintf("name: %s, ph: %s", a, b)
702 }, expected: "name: config,c, ph: FILE\tLoad configuration from FILE"},
703 {name: "config", aliases: []string{"c"}, usage: "Load configuration from `CONFIG`", value: "config.json", prefixer: func(a []string, b string) string {
704 return fmt.Sprintf("name: %s, ph: %s", a, b)
705 }, expected: "name: config,c, ph: CONFIG\tLoad configuration from CONFIG (default: \"config.json\")"},
706 }
707
708 func TestStringFlagApply_SetsAllNames(t *testing.T) {
709 v := "mmm"
710 cmd := &Command{
711 Flags: []Flag{
712 &StringFlag{Name: "hay", Aliases: []string{"H", "hayyy"}, Destination: &v},
713 },
714 }
715
716 err := cmd.Run(buildTestContext(t), []string{"", "--hay", "u", "-H", "yuu", "--hayyy", "YUUUU"})
717 assert.NoError(t, err)
718 assert.Equal(t, "YUUUU", v)
719 }
720
721 func TestStringFlagValueFromCommand(t *testing.T) {
722 f := &StringFlag{Name: "myflag"}
723 cmd := &Command{
724 Flags: []Flag{
725 f,
726 },
727 }
728 require.NoError(t, cmd.Set("myflag", "foobar"))
729 require.Equal(t, "foobar", cmd.String(f.Name))
730 }
731
732 var _ = []struct {
733 name string
734 env string
735 hinter FlagEnvHintFunc
736 expected string
737 }{
738 {"foo", "", func(a []string, b string) string {
739 return fmt.Sprintf("env: %s, str: %s", a, b)
740 }, "env: , str: --foo value\t"},
741 {"f", "", func(a []string, b string) string {
742 return fmt.Sprintf("env: %s, str: %s", a, b)
743 }, "env: , str: -f value\t"},
744 {"foo", "ENV_VAR", func(a []string, b string) string {
745 return fmt.Sprintf("env: %s, str: %s", a, b)
746 }, "env: ENV_VAR, str: --foo value\t"},
747 {"f", "ENV_VAR", func(a []string, b string) string {
748 return fmt.Sprintf("env: %s, str: %s", a, b)
749 }, "env: ENV_VAR, str: -f value\t"},
750 }
751
752 // func TestFlagEnvHinter(t *testing.T) {
753 // defer func() {
754 // FlagEnvHinter = withEnvHint
755 // }()
756 //
757 // for _, test := range envHintFlagTests {
758 // FlagEnvHinter = test.hinter
759 // fl := StringFlag{Name: test.name, Sources: ValueSources{test.env}}
760 // output := fl.String()
761 // if output != test.expected {
762 // t.Errorf("%q does not match %q", output, test.expected)
763 // }
764 // }
765 // }
766
767 var stringSliceFlagTests = []struct {
768 name string
769 aliases []string
770 value []string
771 expected string
772 }{
773 {"foo", nil, []string{}, "--foo string [ --foo string ]\t"},
774 {"f", nil, []string{}, "-f string [ -f string ]\t"},
775 {"f", nil, []string{"Lipstick"}, "-f string [ -f string ]\t(default: \"Lipstick\")"},
776 {"test", nil, []string{"Something"}, "--test string [ --test string ]\t(default: \"Something\")"},
777 {"dee", []string{"d"}, []string{"Inka", "Dinka", "dooo"}, "--dee string, -d string [ --dee string, -d string ]\t(default: \"Inka\", \"Dinka\", \"dooo\")"},
778 }
779
780 func TestStringSliceFlagHelpOutput(t *testing.T) {
781 for _, test := range stringSliceFlagTests {
782 f := &StringSliceFlag{Name: test.name, Aliases: test.aliases, Value: test.value}
783 assert.Equal(t, test.expected, f.String())
784 }
785 }
786
787 func TestStringSliceFlagWithEnvVarHelpOutput(t *testing.T) {
788 t.Setenv("APP_QWWX", "11,4")
789
790 for _, test := range stringSliceFlagTests {
791 fl := &StringSliceFlag{Name: test.name, Aliases: test.aliases, Value: test.value, Sources: EnvVars("APP_QWWX")}
792 output := fl.String()
793
794 expectedSuffix := withEnvHint([]string{"APP_QWWX"}, "")
795 if !strings.HasSuffix(output, expectedSuffix) {
796 t.Errorf("%q does not end with"+expectedSuffix, output)
797 }
798 }
799 }
800
801 func TestStringSliceFlagApply_SetsAllNames(t *testing.T) {
802 fl := &StringSliceFlag{Name: "goat", Aliases: []string{"G", "gooots"}}
803 cmd := &Command{
804 Flags: []Flag{
805 fl,
806 },
807 }
808
809 err := cmd.Run(buildTestContext(t), []string{"", "--goat", "aaa", "-G", "bbb", "--gooots", "eeeee"})
810 assert.NoError(t, err)
811 }
812
813 func TestStringSliceFlagApply_UsesEnvValues_noDefault(t *testing.T) {
814 t.Setenv("MY_GOAT", "vincent van goat,scape goat")
815 fl := &StringSliceFlag{Name: "goat", Sources: EnvVars("MY_GOAT")}
816 cmd := &Command{
817 Flags: []Flag{
818 fl,
819 },
820 }
821
822 err := cmd.Run(buildTestContext(t), []string{""})
823 assert.NoError(t, err)
824 assert.Equal(t, []string{"vincent van goat", "scape goat"}, cmd.Value("goat"))
825 }
826
827 func TestStringSliceFlagApply_UsesEnvValues_withDefault(t *testing.T) {
828 t.Setenv("MY_GOAT", "vincent van goat,scape goat")
829 val := []string{`some default`, `values here`}
830 fl := &StringSliceFlag{Name: "goat", Sources: EnvVars("MY_GOAT"), Value: val}
831 cmd := &Command{
832 Flags: []Flag{
833 fl,
834 },
835 }
836 err := cmd.Run(buildTestContext(t), []string{""})
837 assert.NoError(t, err)
838 assert.Equal(t, []string{"vincent van goat", "scape goat"}, cmd.Value("goat"))
839 }
840
841 func TestStringSliceFlagApply_DefaultValueWithDestination(t *testing.T) {
842 defValue := []string{"UA", "US"}
843 dest := []string{"CA"}
844
845 fl := StringSliceFlag{Name: "country", Value: defValue, Destination: &dest}
846 cmd := &Command{
847 Flags: []Flag{
848 &fl,
849 },
850 }
851
852 err := cmd.Run(buildTestContext(t), []string{""})
853 assert.NoError(t, err)
854 assert.Equal(t, defValue, dest)
855 }
856
857 func TestStringSliceFlagValueFromCommand(t *testing.T) {
858 f := &StringSliceFlag{Name: "myflag"}
859 cmd := &Command{
860 Flags: []Flag{
861 f,
862 },
863 }
864
865 require.NoError(t, cmd.Set("myflag", "a"))
866 require.NoError(t, cmd.Set("myflag", "b"))
867 require.NoError(t, cmd.Set("myflag", "c"))
868 require.Equal(t, []string{"a", "b", "c"}, cmd.StringSlice(f.Name))
869 }
870
871 var intFlagTests = []struct {
872 name string
873 expected string
874 }{
875 {"hats", "--hats int\t(default: 9)"},
876 {"H", "-H int\t(default: 9)"},
877 }
878
879 func TestIntFlagHelpOutput(t *testing.T) {
880 for _, test := range intFlagTests {
881 fl := &Int64Flag{Name: test.name, Value: 9}
882 assert.Equal(t, test.expected, fl.String())
883 }
884 }
885
886 func TestIntFlagWithEnvVarHelpOutput(t *testing.T) {
887 t.Setenv("APP_BAR", "2")
888
889 for _, test := range intFlagTests {
890 fl := &Int64Flag{Name: test.name, Sources: EnvVars("APP_BAR")}
891 output := fl.String()
892
893 expectedSuffix := withEnvHint([]string{"APP_BAR"}, "")
894 if !strings.HasSuffix(output, expectedSuffix) {
895 t.Errorf("%s does not end with"+expectedSuffix, output)
896 }
897 }
898 }
899
900 func TestIntFlagApply_SetsAllNames(t *testing.T) {
901 v := int64(3)
902 cmd := &Command{
903 Flags: []Flag{
904 &Int64Flag{Name: "banana", Aliases: []string{"B", "banannanana"}, Destination: &v},
905 },
906 }
907 r := require.New(t)
908 r.NoError(cmd.Run(buildTestContext(t), []string{"", "--banana", "1", "-B", "2", "--banannanana", "5"}))
909 r.Equal(int64(5), v)
910 }
911
912 func TestIntFlagValueFromCommand(t *testing.T) {
913 fl := &Int64Flag{Name: "myflag"}
914 cmd := &Command{
915 Flags: []Flag{
916 fl,
917 },
918 }
919 require.NoError(t, cmd.Set("myflag", "42"))
920 require.Equal(t, int64(42), cmd.Int64(fl.Name))
921 }
922
923 var uintFlagTests = []struct {
924 name string
925 expected string
926 }{
927 {"nerfs", "--nerfs uint\t(default: 41)"},
928 {"N", "-N uint\t(default: 41)"},
929 }
930
931 func TestUintFlagHelpOutput(t *testing.T) {
932 for _, test := range uintFlagTests {
933 fl := &Uint64Flag{Name: test.name, Value: 41}
934 assert.Equal(t, test.expected, fl.String())
935 }
936 }
937
938 func TestUintFlagWithEnvVarHelpOutput(t *testing.T) {
939 t.Setenv("APP_BAR", "2")
940
941 for _, test := range uintFlagTests {
942 fl := &Uint64Flag{Name: test.name, Sources: EnvVars("APP_BAR")}
943 output := fl.String()
944
945 expectedSuffix := withEnvHint([]string{"APP_BAR"}, "")
946 if !strings.HasSuffix(output, expectedSuffix) {
947 t.Errorf("%s does not end with"+expectedSuffix, output)
948 }
949 }
950 }
951
952 func TestUintFlagValueFromCommand(t *testing.T) {
953 fl := &Uint64Flag{Name: "myflag"}
954 cmd := &Command{
955 Flags: []Flag{
956 fl,
957 },
958 }
959 require.NoError(t, cmd.Set("myflag", "42"))
960 require.Equal(t, uint64(42), cmd.Uint64(fl.Name))
961 }
962
963 var uint64FlagTests = []struct {
964 name string
965 expected string
966 }{
967 {"gerfs", "--gerfs uint\t(default: 8589934582)"},
968 {"G", "-G uint\t(default: 8589934582)"},
969 }
970
971 func TestUint64FlagHelpOutput(t *testing.T) {
972 for _, test := range uint64FlagTests {
973 fl := Uint64Flag{Name: test.name, Value: 8589934582}
974 assert.Equal(t, test.expected, fl.String())
975 }
976 }
977
978 func TestUint64FlagWithEnvVarHelpOutput(t *testing.T) {
979 t.Setenv("APP_BAR", "2")
980
981 for _, test := range uint64FlagTests {
982 fl := &Uint64Flag{Name: test.name, Sources: EnvVars("APP_BAR")}
983 output := fl.String()
984
985 expectedSuffix := withEnvHint([]string{"APP_BAR"}, "")
986 if !strings.HasSuffix(output, expectedSuffix) {
987 t.Errorf("%s does not end with"+expectedSuffix, output)
988 }
989 }
990 }
991
992 func TestUint64FlagValueFromCommand(t *testing.T) {
993 f := &Uint64Flag{Name: "myflag"}
994 cmd := &Command{
995 Flags: []Flag{
996 f,
997 },
998 }
999 require.NoError(t, cmd.Set("myflag", "42"))
1000 require.Equal(t, uint64(42), cmd.Uint64(f.Name))
1001 }
1002
1003 var durationFlagTests = []struct {
1004 name string
1005 expected string
1006 }{
1007 {"hooting", "--hooting duration\t(default: 1s)"},
1008 {"H", "-H duration\t(default: 1s)"},
1009 }
1010
1011 func TestDurationFlagHelpOutput(t *testing.T) {
1012 for _, test := range durationFlagTests {
1013 fl := &DurationFlag{Name: test.name, Value: 1 * time.Second}
1014 assert.Equal(t, test.expected, fl.String())
1015 }
1016 }
1017
1018 func TestDurationFlagWithEnvVarHelpOutput(t *testing.T) {
1019 t.Setenv("APP_BAR", "2h3m6s")
1020
1021 for _, test := range durationFlagTests {
1022 fl := &DurationFlag{Name: test.name, Sources: EnvVars("APP_BAR")}
1023 output := fl.String()
1024
1025 expectedSuffix := withEnvHint([]string{"APP_BAR"}, "")
1026 if !strings.HasSuffix(output, expectedSuffix) {
1027 t.Errorf("%s does not end with"+expectedSuffix, output)
1028 }
1029 }
1030 }
1031
1032 func TestDurationFlagApply_SetsAllNames(t *testing.T) {
1033 v := time.Second * 20
1034 cmd := &Command{
1035 Flags: []Flag{
1036 &DurationFlag{Name: "howmuch", Aliases: []string{"H", "whyyy"}, Destination: &v},
1037 },
1038 }
1039 err := cmd.Run(buildTestContext(t), []string{"", "--howmuch", "30s", "-H", "5m", "--whyyy", "30h"})
1040 assert.NoError(t, err)
1041 assert.Equal(t, time.Hour*30, v)
1042 }
1043
1044 func TestDurationFlagValueFromCommand(t *testing.T) {
1045 f := &DurationFlag{Name: "myflag"}
1046 cmd := &Command{
1047 Flags: []Flag{
1048 f,
1049 },
1050 }
1051 require.NoError(t, cmd.Set("myflag", "42s"))
1052 require.Equal(t, 42*time.Second, cmd.Duration(f.Name))
1053 }
1054
1055 var intSliceFlagTests = []struct {
1056 name string
1057 aliases []string
1058 value []int64
1059 expected string
1060 }{
1061 {"heads", nil, []int64{}, "--heads int [ --heads int ]\t"},
1062 {"H", nil, []int64{}, "-H int [ -H int ]\t"},
1063 {"H", []string{"heads"}, []int64{9, 3}, "-H int, --heads int [ -H int, --heads int ]\t(default: 9, 3)"},
1064 }
1065
1066 func TestIntSliceFlagHelpOutput(t *testing.T) {
1067 for _, test := range intSliceFlagTests {
1068 fl := &Int64SliceFlag{Name: test.name, Aliases: test.aliases, Value: test.value}
1069 assert.Equal(t, test.expected, fl.String())
1070 }
1071 }
1072
1073 func TestIntSliceFlagWithEnvVarHelpOutput(t *testing.T) {
1074 t.Setenv("APP_SMURF", "42,3")
1075
1076 for _, test := range intSliceFlagTests {
1077 fl := &Int64SliceFlag{Name: test.name, Aliases: test.aliases, Value: test.value, Sources: EnvVars("APP_SMURF")}
1078 output := fl.String()
1079
1080 expectedSuffix := withEnvHint([]string{"APP_SMURF"}, "")
1081 if !strings.HasSuffix(output, expectedSuffix) {
1082 t.Errorf("%q does not end with"+expectedSuffix, output)
1083 }
1084 }
1085 }
1086
1087 func TestIntSliceFlagApply_SetsAllNames(t *testing.T) {
1088 fl := &Int64SliceFlag{Name: "bits", Aliases: []string{"B", "bips"}}
1089 cmd := &Command{
1090 Flags: []Flag{
1091 fl,
1092 },
1093 }
1094 err := cmd.Run(buildTestContext(t), []string{"", "--bits", "23", "-B", "3", "--bips", "99"})
1095 assert.NoError(t, err)
1096 }
1097
1098 func TestIntSliceFlagApply_UsesEnvValues_noDefault(t *testing.T) {
1099 t.Setenv("MY_GOAT", "1 , 2")
1100
1101 fl := &Int64SliceFlag{Name: "goat", Sources: EnvVars("MY_GOAT")}
1102 cmd := &Command{
1103 Flags: []Flag{
1104 fl,
1105 },
1106 }
1107 r := require.New(t)
1108 r.NoError(cmd.Run(buildTestContext(t), []string{""}))
1109 r.NoError(fl.PostParse())
1110 r.Equal([]int64{1, 2}, cmd.Value("goat"))
1111 }
1112
1113 func TestIntSliceFlagApply_UsesEnvValues_withDefault(t *testing.T) {
1114 t.Setenv("MY_GOAT", "1 , 2")
1115 val := []int64{3, 4}
1116 fl := &Int64SliceFlag{Name: "goat", Sources: EnvVars("MY_GOAT"), Value: val}
1117 cmd := &Command{
1118 Flags: []Flag{
1119 fl,
1120 },
1121 }
1122 r := require.New(t)
1123 r.NoError(cmd.Run(buildTestContext(t), []string{""}))
1124 r.Equal([]int64{3, 4}, val)
1125 r.Equal([]int64{1, 2}, cmd.Value("goat"))
1126 }
1127
1128 func TestIntSliceFlagApply_DefaultValueWithDestination(t *testing.T) {
1129 defValue := []int64{1, 2}
1130 dest := []int64{3}
1131
1132 fl := &Int64SliceFlag{Name: "country", Value: defValue, Destination: &dest}
1133 cmd := &Command{
1134 Flags: []Flag{
1135 fl,
1136 },
1137 }
1138 err := cmd.Run(buildTestContext(t), []string{""})
1139 assert.NoError(t, err)
1140 assert.Equal(t, defValue, dest)
1141 }
1142
1143 func TestIntSliceFlagApply_ParentContext(t *testing.T) {
1144 _ = (&Command{
1145 Flags: []Flag{
1146 &Int64SliceFlag{Name: "numbers", Aliases: []string{"n"}, Value: []int64{1, 2, 3}},
1147 },
1148 Commands: []*Command{
1149 {
1150 Name: "child",
1151 Action: func(_ context.Context, cmd *Command) error {
1152 require.Equalf(t, []int64{1, 2, 3}, cmd.Int64Slice("numbers"), "child context unable to view parent flag")
1153
1154 return nil
1155 },
1156 },
1157 },
1158 }).Run(buildTestContext(t), []string{"run", "child"})
1159 }
1160
1161 func TestIntSliceFlag_SetFromParentCommand(t *testing.T) {
1162 fl := &Int64SliceFlag{Name: "numbers", Aliases: []string{"n"}, Value: []int64{1, 2, 3, 4}}
1163
1164 cmd := &Command{
1165 parent: &Command{
1166 Flags: []Flag{
1167 fl,
1168 },
1169 },
1170 }
1171
1172 require.Equalf(t, []int64{1, 2, 3, 4}, cmd.Int64Slice("numbers"), "child context unable to view parent flag")
1173 }
1174
1175 func TestIntSliceFlagValueFromCommand(t *testing.T) {
1176 f := &Int64SliceFlag{Name: "myflag"}
1177 cmd := &Command{
1178 Flags: []Flag{
1179 f,
1180 },
1181 }
1182 require.NoError(t, cmd.Set("myflag", "1"))
1183 require.NoError(t, cmd.Set("myflag", "2"))
1184 require.NoError(t, cmd.Set("myflag", "3"))
1185 require.Equal(t, []int64{1, 2, 3}, cmd.Int64Slice(f.Name))
1186 }
1187
1188 var uintSliceFlagTests = []struct {
1189 name string
1190 aliases []string
1191 value []uint64
1192 expected string
1193 }{
1194 {"heads", nil, []uint64{}, "--heads uint [ --heads uint ]\t"},
1195 {"H", nil, []uint64{}, "-H uint [ -H uint ]\t"},
1196 {
1197 "heads",
1198 []string{"H"},
1199 []uint64{2, 17179869184},
1200 "--heads uint, -H uint [ --heads uint, -H uint ]\t(default: 2, 17179869184)",
1201 },
1202 }
1203
1204 func TestUintSliceFlagHelpOutput(t *testing.T) {
1205 for _, test := range uintSliceFlagTests {
1206 t.Run(test.name, func(t *testing.T) {
1207 fl := &Uint64SliceFlag{Name: test.name, Aliases: test.aliases, Value: test.value}
1208 require.Equal(t, test.expected, fl.String())
1209 })
1210 }
1211 }
1212
1213 func TestUintSliceFlagWithEnvVarHelpOutput(t *testing.T) {
1214 t.Setenv("APP_SMURF", "42,17179869184")
1215
1216 for _, test := range uintSliceFlagTests {
1217 fl := &Uint64SliceFlag{Name: test.name, Value: test.value, Sources: EnvVars("APP_SMURF")}
1218 output := fl.String()
1219
1220 expectedSuffix := withEnvHint([]string{"APP_SMURF"}, "")
1221 if !strings.HasSuffix(output, expectedSuffix) {
1222 t.Errorf("%q does not end with"+expectedSuffix, output)
1223 }
1224 }
1225 }
1226
1227 func TestUintSliceFlagApply_SetsAllNames(t *testing.T) {
1228 fl := &Uint64SliceFlag{Name: "bits", Aliases: []string{"B", "bips"}}
1229 cmd := &Command{
1230 Flags: []Flag{
1231 fl,
1232 },
1233 }
1234 err := cmd.Run(buildTestContext(t), []string{"", "--bits", "23", "-B", "3", "--bips", "99"})
1235 assert.NoError(t, err)
1236 }
1237
1238 func TestUintSliceFlagApply_UsesEnvValues_noDefault(t *testing.T) {
1239 t.Setenv("MY_GOAT", "1 , 2")
1240
1241 fl := &Uint64SliceFlag{Name: "goat", Sources: EnvVars("MY_GOAT")}
1242 cmd := &Command{
1243 Flags: []Flag{
1244 fl,
1245 },
1246 }
1247 r := require.New(t)
1248 r.NoError(cmd.Run(buildTestContext(t), []string{""}))
1249 r.Equal([]uint64{1, 2}, cmd.Value("goat"))
1250 }
1251
1252 func TestUintSliceFlagApply_UsesEnvValues_withDefault(t *testing.T) {
1253 t.Setenv("MY_GOAT", "1 , 2")
1254 val := NewUint64Slice(3, 4)
1255 fl := &Uint64SliceFlag{Name: "goat", Sources: EnvVars("MY_GOAT"), Value: val.Value()}
1256 cmd := &Command{
1257 Flags: []Flag{
1258 fl,
1259 },
1260 }
1261 r := require.New(t)
1262 r.NoError(cmd.Run(buildTestContext(t), []string{""}))
1263 r.Equal([]uint64{3, 4}, val.Value())
1264 r.Equal([]uint64{1, 2}, cmd.Value("goat"))
1265 }
1266
1267 func TestUintSliceFlagApply_DefaultValueWithDestination(t *testing.T) {
1268 defValue := []uint64{1, 2}
1269 var dest []uint64
1270
1271 fl := &Uint64SliceFlag{Name: "country", Value: defValue, Destination: &dest}
1272 cmd := &Command{
1273 Flags: []Flag{
1274 fl,
1275 },
1276 }
1277 err := cmd.Run(buildTestContext(t), []string{""})
1278 assert.NoError(t, err)
1279 assert.Equal(t, defValue, dest)
1280 }
1281
1282 func TestUint64SliceFlagApply_ParentContext(t *testing.T) {
1283 _ = (&Command{
1284 Flags: []Flag{
1285 &Uint64SliceFlag{Name: "numbers", Aliases: []string{"n"}, Value: []uint64{1, 2, 3}},
1286 },
1287 Commands: []*Command{
1288 {
1289 Name: "child",
1290 Action: func(_ context.Context, cmd *Command) error {
1291 require.Equalf(
1292 t, []uint64{1, 2, 3}, cmd.Uint64Slice("numbers"),
1293 "child context unable to view parent flag",
1294 )
1295 return nil
1296 },
1297 },
1298 },
1299 }).Run(buildTestContext(t), []string{"run", "child"})
1300 }
1301
1302 func TestUintSliceFlag_SetFromParentCommand(t *testing.T) {
1303 fl := &UintSliceFlag{Name: "numbers", Aliases: []string{"n"}, Value: []uint{1, 2, 3, 4}}
1304 cmd := &Command{
1305 parent: &Command{
1306 Flags: []Flag{
1307 fl,
1308 },
1309 },
1310 }
1311
1312 r := require.New(t)
1313 r.Equalf(
1314 []uint{1, 2, 3, 4},
1315 cmd.UintSlice("numbers"),
1316 "child context unable to view parent flag",
1317 )
1318 }
1319
1320 func TestUintSliceFlag_ReturnNil(t *testing.T) {
1321 fl := &Uint64SliceFlag{}
1322
1323 r := require.New(t)
1324 cmd := &Command{
1325 parent: &Command{
1326 Flags: []Flag{
1327 fl,
1328 },
1329 },
1330 }
1331 r.Equalf(
1332 []uint64(nil),
1333 cmd.Uint64Slice("numbers"),
1334 "child context unable to view parent flag",
1335 )
1336 }
1337
1338 var uint64SliceFlagTests = []struct {
1339 name string
1340 aliases []string
1341 value []uint64
1342 expected string
1343 }{
1344 {"heads", nil, []uint64{}, "--heads uint [ --heads uint ]\t"},
1345 {"H", nil, []uint64{}, "-H uint [ -H uint ]\t"},
1346 {
1347 "heads",
1348 []string{"H"},
1349 []uint64{2, 17179869184},
1350 "--heads uint, -H uint [ --heads uint, -H uint ]\t(default: 2, 17179869184)",
1351 },
1352 }
1353
1354 func TestUint64SliceFlagHelpOutput(t *testing.T) {
1355 for _, test := range uint64SliceFlagTests {
1356 fl := Uint64SliceFlag{Name: test.name, Aliases: test.aliases, Value: test.value}
1357 assert.Equal(t, test.expected, fl.String())
1358 }
1359 }
1360
1361 func TestUint64SliceFlagWithEnvVarHelpOutput(t *testing.T) {
1362 t.Setenv("APP_SMURF", "42,17179869184")
1363
1364 for _, test := range uint64SliceFlagTests {
1365 fl := Uint64SliceFlag{Name: test.name, Value: test.value, Sources: EnvVars("APP_SMURF")}
1366 output := fl.String()
1367
1368 expectedSuffix := withEnvHint([]string{"APP_SMURF"}, "")
1369 if !strings.HasSuffix(output, expectedSuffix) {
1370 t.Errorf("%q does not end with"+expectedSuffix, output)
1371 }
1372 }
1373 }
1374
1375 func TestUint64SliceFlagApply_SetsAllNames(t *testing.T) {
1376 fl := Uint64SliceFlag{Name: "bits", Aliases: []string{"B", "bips"}}
1377 cmd := &Command{
1378 Flags: []Flag{
1379 &fl,
1380 },
1381 }
1382 err := cmd.Run(buildTestContext(t), []string{"", "--bits", "23", "-B", "3", "--bips", "99"})
1383 assert.NoError(t, err)
1384 }
1385
1386 func TestUint64SliceFlagApply_UsesEnvValues_noDefault(t *testing.T) {
1387 t.Setenv("MY_GOAT", "1 , 2")
1388 fl := Uint64SliceFlag{Name: "goat", Sources: EnvVars("MY_GOAT")}
1389 cmd := &Command{
1390 Flags: []Flag{
1391 &fl,
1392 },
1393 }
1394 assert.NoError(t, cmd.Run(buildTestContext(t), []string{""}))
1395 assert.Equal(t, []uint64{1, 2}, cmd.Value("goat"))
1396 }
1397
1398 func TestUint64SliceFlagApply_UsesEnvValues_withDefault(t *testing.T) {
1399 t.Setenv("MY_GOAT", "1 , 2")
1400 val := []uint64{3, 4}
1401 fl := Uint64SliceFlag{Name: "goat", Sources: EnvVars("MY_GOAT"), Value: val}
1402 cmd := &Command{
1403 Flags: []Flag{
1404 &fl,
1405 },
1406 }
1407 assert.NoError(t, cmd.Run(buildTestContext(t), []string{""}))
1408 assert.Equal(t, []uint64{1, 2}, cmd.Value("goat"))
1409 }
1410
1411 func TestUint64SliceFlagApply_DefaultValueWithDestination(t *testing.T) {
1412 defValue := []uint64{1, 2}
1413 dest := []uint64{3}
1414
1415 fl := Uint64SliceFlag{Name: "country", Value: defValue, Destination: &dest}
1416 cmd := &Command{
1417 Flags: []Flag{
1418 &fl,
1419 },
1420 }
1421
1422 err := cmd.Run(buildTestContext(t), []string{""})
1423 assert.NoError(t, err)
1424
1425 assert.Equal(t, defValue, dest)
1426 }
1427
1428 func TestUint64SliceFlagApply_ParentCommand(t *testing.T) {
1429 _ = (&Command{
1430 Flags: []Flag{
1431 &Uint64SliceFlag{Name: "numbers", Aliases: []string{"n"}, Value: []uint64{1, 2, 3}},
1432 },
1433 Commands: []*Command{
1434 {
1435 Name: "child",
1436 Action: func(_ context.Context, cmd *Command) error {
1437 require.Equalf(
1438 t, []uint64{1, 2, 3}, cmd.Uint64Slice("numbers"),
1439 "child context unable to view parent flag",
1440 )
1441 return nil
1442 },
1443 },
1444 },
1445 }).Run(buildTestContext(t), []string{"run", "child"})
1446 }
1447
1448 func TestUint64SliceFlag_SetFromParentCommand(t *testing.T) {
1449 fl := &Uint64SliceFlag{Name: "numbers", Aliases: []string{"n"}, Value: []uint64{1, 2, 3, 4}}
1450 cmd := &Command{
1451 parent: &Command{
1452 Flags: []Flag{
1453 fl,
1454 },
1455 },
1456 }
1457 r := require.New(t)
1458 r.Equalf(
1459 []uint64{1, 2, 3, 4}, cmd.Uint64Slice("numbers"),
1460 "child context unable to view parent flag",
1461 )
1462 }
1463
1464 func TestUint64SliceFlag_ReturnNil(t *testing.T) {
1465 fl := &Uint64SliceFlag{}
1466 cmd := &Command{
1467 parent: &Command{
1468 Flags: []Flag{
1469 fl,
1470 },
1471 },
1472 }
1473 r := require.New(t)
1474 r.Equalf(
1475 []uint64(nil), cmd.Uint64Slice("numbers"),
1476 "child context unable to view parent flag",
1477 )
1478 }
1479
1480 var float64FlagTests = []struct {
1481 name string
1482 expected string
1483 }{
1484 {"hooting", "--hooting float\t(default: 0.1)"},
1485 {"H", "-H float\t(default: 0.1)"},
1486 }
1487
1488 func TestFloat64FlagHelpOutput(t *testing.T) {
1489 for _, test := range float64FlagTests {
1490 f := &FloatFlag{Name: test.name, Value: 0.1}
1491 assert.Equal(t, test.expected, f.String())
1492 }
1493 }
1494
1495 func TestFloat64FlagWithEnvVarHelpOutput(t *testing.T) {
1496 t.Setenv("APP_BAZ", "99.4")
1497
1498 for _, test := range float64FlagTests {
1499 fl := &FloatFlag{Name: test.name, Sources: EnvVars("APP_BAZ")}
1500 output := fl.String()
1501
1502 expectedSuffix := withEnvHint([]string{"APP_BAZ"}, "")
1503 if !strings.HasSuffix(output, expectedSuffix) {
1504 t.Errorf("%s does not end with"+expectedSuffix, output)
1505 }
1506 }
1507 }
1508
1509 func TestFloat64FlagApply_SetsAllNames(t *testing.T) {
1510 v := 99.1
1511 fl := FloatFlag{Name: "noodles", Aliases: []string{"N", "nurbles"}, Destination: &v}
1512 cmd := &Command{
1513 Flags: []Flag{
1514 &fl,
1515 },
1516 }
1517
1518 assert.NoError(t, cmd.Run(buildTestContext(t), []string{"", "--noodles", "1.3", "-N", "11", "--nurbles", "43.33333"}))
1519 assert.Equal(t, float64(43.33333), v)
1520 }
1521
1522 func TestFloat64FlagValueFromCommand(t *testing.T) {
1523 fl := &FloatFlag{Name: "myflag"}
1524 cmd := &Command{
1525 Flags: []Flag{
1526 fl,
1527 },
1528 }
1529 require.NoError(t, cmd.Set("myflag", "1.23"))
1530 require.Equal(t, 1.23, cmd.Float(fl.Name))
1531 }
1532
1533 var float64SliceFlagTests = []struct {
1534 name string
1535 aliases []string
1536 value []float64
1537 expected string
1538 }{
1539 {"heads", nil, []float64{}, "--heads float [ --heads float ]\t"},
1540 {"H", nil, []float64{}, "-H float [ -H float ]\t"},
1541 {
1542 "heads",
1543 []string{"H"},
1544 []float64{0.1234, -10.5},
1545 "--heads float, -H float [ --heads float, -H float ]\t(default: 0.1234, -10.5)",
1546 },
1547 }
1548
1549 func TestFloat64SliceFlagHelpOutput(t *testing.T) {
1550 for _, test := range float64SliceFlagTests {
1551 fl := FloatSliceFlag{Name: test.name, Aliases: test.aliases, Value: test.value}
1552 assert.Equal(t, test.expected, fl.String())
1553 }
1554 }
1555
1556 func TestFloat64SliceFlagWithEnvVarHelpOutput(t *testing.T) {
1557 t.Setenv("APP_SMURF", "0.1234,-10.5")
1558 for _, test := range float64SliceFlagTests {
1559 fl := FloatSliceFlag{Name: test.name, Value: test.value, Sources: EnvVars("APP_SMURF")}
1560 output := fl.String()
1561
1562 expectedSuffix := withEnvHint([]string{"APP_SMURF"}, "")
1563 if !strings.HasSuffix(output, expectedSuffix) {
1564 t.Errorf("%q does not end with"+expectedSuffix, output)
1565 }
1566 }
1567 }
1568
1569 func TestFloat64SliceFlagApply_SetsAllNames(t *testing.T) {
1570 fl := FloatSliceFlag{Name: "bits", Aliases: []string{"B", "bips"}}
1571 cmd := &Command{
1572 Flags: []Flag{
1573 &fl,
1574 },
1575 }
1576
1577 assert.NoError(t, cmd.Run(buildTestContext(t), []string{"", "--bits", "23", "-B", "3", "--bips", "99"}))
1578 }
1579
1580 func TestFloat64SliceFlagApply_UsesEnvValues_noDefault(t *testing.T) {
1581 t.Setenv("MY_GOAT", "1.0 , 2.0")
1582 fl := FloatSliceFlag{Name: "goat", Sources: EnvVars("MY_GOAT")}
1583 cmd := &Command{
1584 Flags: []Flag{
1585 &fl,
1586 },
1587 }
1588
1589 assert.NoError(t, cmd.Run(buildTestContext(t), []string{""}))
1590 assert.Equal(t, []float64{1, 2}, cmd.Value("goat"))
1591 }
1592
1593 func TestFloat64SliceFlagApply_UsesEnvValues_withDefault(t *testing.T) {
1594 t.Setenv("MY_GOAT", "1.0 , 2.0")
1595 val := []float64{3.0, 4.0}
1596 fl := FloatSliceFlag{Name: "goat", Sources: EnvVars("MY_GOAT"), Value: val}
1597 cmd := &Command{
1598 Flags: []Flag{
1599 &fl,
1600 },
1601 }
1602
1603 assert.NoError(t, cmd.Run(buildTestContext(t), []string{""}))
1604 assert.Equal(t, []float64{1, 2}, cmd.Value("goat"))
1605 }
1606
1607 func TestFloat64SliceFlagApply_DefaultValueWithDestination(t *testing.T) {
1608 defValue := []float64{1.0, 2.0}
1609 dest := []float64{3}
1610
1611 fl := FloatSliceFlag{Name: "country", Value: defValue, Destination: &dest}
1612 cmd := &Command{
1613 Flags: []Flag{
1614 &fl,
1615 },
1616 }
1617
1618 assert.NoError(t, cmd.Run(buildTestContext(t), []string{""}))
1619 assert.Equal(t, defValue, dest)
1620 }
1621
1622 func TestFloat64SliceFlagValueFromCommand(t *testing.T) {
1623 fl := FloatSliceFlag{Name: "myflag"}
1624 cmd := &Command{
1625 Flags: []Flag{
1626 &fl,
1627 },
1628 }
1629 assert.NoError(t, cmd.Run(buildTestContext(t), []string{""}))
1630 require.NoError(t, cmd.Set("myflag", "1.23"))
1631 require.NoError(t, cmd.Set("myflag", "4.56"))
1632 require.Equal(t, []float64{1.23, 4.56}, cmd.FloatSlice(fl.Name))
1633 }
1634
1635 func TestFloat64SliceFlagApply_ParentCommand(t *testing.T) {
1636 _ = (&Command{
1637 Flags: []Flag{
1638 &FloatSliceFlag{Name: "numbers", Aliases: []string{"n"}, Value: []float64{1.0, 2.0, 3.0}},
1639 },
1640 Commands: []*Command{
1641 {
1642 Name: "child",
1643 Action: func(_ context.Context, cmd *Command) error {
1644 require.Equalf(t, []float64{1.0, 2.0, 3.0}, cmd.FloatSlice("numbers"), "child context unable to view parent flag")
1645 return nil
1646 },
1647 },
1648 },
1649 }).Run(buildTestContext(t), []string{"run", "child"})
1650 }
1651
1652 var genericFlagTests = []struct {
1653 name string
1654 value Value
1655 expected string
1656 }{
1657 {"toads", &Parser{"abc", "def"}, "--toads value\ttest flag (default: abc,def)"},
1658 {"t", &Parser{"abc", "def"}, "-t value\ttest flag (default: abc,def)"},
1659 }
1660
1661 func TestGenericFlagHelpOutput(t *testing.T) {
1662 for _, test := range genericFlagTests {
1663 fl := &GenericFlag{Name: test.name, Value: test.value, Usage: "test flag"}
1664 assert.Equal(t, test.expected, fl.String())
1665 }
1666 }
1667
1668 func TestGenericFlagWithEnvVarHelpOutput(t *testing.T) {
1669 t.Setenv("APP_ZAP", "3")
1670
1671 for _, test := range genericFlagTests {
1672 fl := &GenericFlag{Name: test.name, Sources: EnvVars("APP_ZAP")}
1673 output := fl.String()
1674
1675 expectedSuffix := withEnvHint([]string{"APP_ZAP"}, "")
1676 if !strings.HasSuffix(output, expectedSuffix) {
1677 t.Errorf("%s does not end with"+expectedSuffix, output)
1678 }
1679 }
1680 }
1681
1682 func TestGenericFlagApply_SetsAllNames(t *testing.T) {
1683 fl := GenericFlag{Name: "orbs", Aliases: []string{"O", "obrs"}, Value: &Parser{}}
1684 cmd := &Command{
1685 Flags: []Flag{
1686 &fl,
1687 },
1688 }
1689
1690 assert.NoError(t, cmd.Run(buildTestContext(t), []string{"", "--orbs", "eleventy,3", "-O", "4,bloop", "--obrs", "19,s"}))
1691 }
1692
1693 func TestGenericFlagValueFromCommand(t *testing.T) {
1694 cmd := &Command{
1695 Name: "foo",
1696 Flags: []Flag{
1697 &GenericFlag{Name: "myflag", Value: &Parser{}},
1698 },
1699 }
1700
1701 assert.NoError(t, cmd.Run(buildTestContext(t), []string{"foo", "--myflag", "abc,def"}))
1702 assert.Equal(t, &Parser{"abc", "def"}, cmd.Generic("myflag"))
1703 assert.Nil(t, cmd.Generic("someother"))
1704 }
1705
1706 func TestParseGenericFromEnv(t *testing.T) {
1707 t.Setenv("APP_SERVE", "20,30")
1708 cmd := &Command{
1709 Flags: []Flag{
1710 &GenericFlag{
1711 Name: "serve",
1712 Aliases: []string{"s"},
1713 Value: &Parser{},
1714 Sources: EnvVars("APP_SERVE"),
1715 },
1716 },
1717 Action: func(ctx context.Context, cmd *Command) error {
1718 if !reflect.DeepEqual(cmd.Generic("serve"), &Parser{"20", "30"}) {
1719 t.Errorf("main name not set from env")
1720 }
1721 if !reflect.DeepEqual(cmd.Generic("s"), &Parser{"20", "30"}) {
1722 t.Errorf("short name not set from env")
1723 }
1724 return nil
1725 },
1726 }
1727 assert.NoError(t, cmd.Run(buildTestContext(t), []string{"run"}))
1728 }
1729
1730 func TestFlagActionFromEnv(t *testing.T) {
1731 t.Setenv("X", "42")
1732 x := 0
1733
1734 cmd := &Command{
1735 Flags: []Flag{
1736 &IntFlag{
1737 Name: "x",
1738 Sources: EnvVars("X"),
1739 Action: func(ctx context.Context, cmd *Command, v int) error {
1740 x = v
1741 return nil
1742 },
1743 },
1744 },
1745 }
1746
1747 assert.NoError(t, cmd.Run(buildTestContext(t), []string{"run"}))
1748 assert.Equal(t, cmd.Int("x"), 42)
1749 assert.Equal(t, x, 42)
1750 }
1751
1752 func TestParseShortOptionBoolError(t *testing.T) {
1753 cmd := buildMinimalTestCommand()
1754 cmd.UseShortOptionHandling = true
1755 cmd.Flags = []Flag{
1756 &BoolFlag{Name: "debug", Aliases: []string{"d"}},
1757 &BoolFlag{Name: "verbose", Aliases: []string{"v"}},
1758 }
1759
1760 err := cmd.Run(buildTestContext(t), []string{"run", "-vd=notabool"})
1761 assert.Error(t, err, "expected error parsing invalid bool")
1762 }
1763
1764 func TestParseShortOptionIntError(t *testing.T) {
1765 cmd := buildMinimalTestCommand()
1766 cmd.Flags = []Flag{
1767 &IntFlag{Name: "port", Aliases: []string{"p"}},
1768 &BoolFlag{Name: "debug", Aliases: []string{"d"}},
1769 }
1770
1771 err := cmd.Run(buildTestContext(t), []string{"run", "-dp=notanint"})
1772 assert.Error(t, err, "expected error parsing invalid int")
1773 }
1774
1775 func TestParseMultiString(t *testing.T) {
1776 _ = (&Command{
1777 Flags: []Flag{
1778 &StringFlag{Name: "serve", Aliases: []string{"s"}},
1779 },
1780 Action: func(_ context.Context, cmd *Command) error {
1781 assert.Equal(t, "10", cmd.String("serve"), "main name not set")
1782 assert.Equal(t, "10", cmd.String("s"), "short name not set")
1783 return nil
1784 },
1785 }).Run(buildTestContext(t), []string{"run", "-s", "10"})
1786 }
1787
1788 func TestParseDestinationString(t *testing.T) {
1789 var dest string
1790 _ = (&Command{
1791 Flags: []Flag{
1792 &StringFlag{
1793 Name: "dest",
1794 Destination: &dest,
1795 },
1796 },
1797 Action: func(context.Context, *Command) error {
1798 assert.Equal(t, "10", dest, "expected destination String 10")
1799 return nil
1800 },
1801 }).Run(buildTestContext(t), []string{"run", "--dest", "10"})
1802 }
1803
1804 func TestParseMultiStringFromEnv(t *testing.T) {
1805 t.Setenv("APP_COUNT", "20")
1806
1807 _ = (&Command{
1808 Flags: []Flag{
1809 &StringFlag{Name: "count", Aliases: []string{"c"}, Sources: EnvVars("APP_COUNT")},
1810 },
1811 Action: func(_ context.Context, cmd *Command) error {
1812 assert.Equal(t, "20", cmd.String("count"), "main name not set")
1813 assert.Equal(t, "20", cmd.String("c"), "short name not set")
1814 return nil
1815 },
1816 }).Run(buildTestContext(t), []string{"run"})
1817 }
1818
1819 func TestParseMultiStringFromEnvCascade(t *testing.T) {
1820 t.Setenv("APP_COUNT", "20")
1821
1822 _ = (&Command{
1823 Flags: []Flag{
1824 &StringFlag{Name: "count", Aliases: []string{"c"}, Sources: EnvVars("COMPAT_COUNT", "APP_COUNT")},
1825 },
1826 Action: func(_ context.Context, cmd *Command) error {
1827 assert.Equal(t, "20", cmd.String("count"), "main name not set")
1828 assert.Equal(t, "20", cmd.String("c"), "short name not set")
1829 return nil
1830 },
1831 }).Run(buildTestContext(t), []string{"run"})
1832 }
1833
1834 func TestParseMultiStringSlice(t *testing.T) {
1835 _ = (&Command{
1836 Flags: []Flag{
1837 &StringSliceFlag{Name: "serve", Aliases: []string{"s"}, Value: []string{}},
1838 },
1839 Action: func(_ context.Context, cmd *Command) error {
1840 expected := []string{"10", "20"}
1841 assert.Equal(t, expected, cmd.StringSlice("serve"), "main name not set")
1842 assert.Equal(t, expected, cmd.StringSlice("s"), "short name not set")
1843 return nil
1844 },
1845 }).Run(buildTestContext(t), []string{"run", "-s", "10", "-s", "20"})
1846 }
1847
1848 func TestParseMultiStringSliceWithDefaults(t *testing.T) {
1849 _ = (&Command{
1850 Flags: []Flag{
1851 &StringSliceFlag{Name: "serve", Aliases: []string{"s"}, Value: []string{"9", "2"}},
1852 },
1853 Action: func(_ context.Context, cmd *Command) error {
1854 expected := []string{"10", "20"}
1855 assert.Equal(t, expected, cmd.StringSlice("serve"), "main name not set")
1856 assert.Equal(t, expected, cmd.StringSlice("s"), "short name not set")
1857 return nil
1858 },
1859 }).Run(buildTestContext(t), []string{"run", "-s", "10", "-s", "20"})
1860 }
1861
1862 func TestParseMultiStringSliceWithDestination(t *testing.T) {
1863 dest := []string{}
1864
1865 _ = (&Command{
1866 Flags: []Flag{
1867 &StringSliceFlag{Name: "serve", Aliases: []string{"s"}, Destination: &dest},
1868 },
1869 Action: func(_ context.Context, cmd *Command) error {
1870 expected := []string{"10", "20"}
1871 assert.Equal(t, expected, dest, "destination val not set")
1872 return nil
1873 },
1874 }).Run(buildTestContext(t), []string{"run", "-s", "10", "-s", "20"})
1875 }
1876
1877 func TestParseMultiStringSliceWithDestinationAndEnv(t *testing.T) {
1878 t.Setenv("APP_INTERVALS", "20,30,40")
1879
1880 dest := []string{}
1881 _ = (&Command{
1882 Flags: []Flag{
1883 &StringSliceFlag{Name: "serve", Aliases: []string{"s"}, Destination: &dest, Sources: EnvVars("APP_INTERVALS")},
1884 },
1885 Action: func(_ context.Context, cmd *Command) error {
1886 expected := []string{"10", "20"}
1887 assert.Equal(t, expected, dest, "destination val not set")
1888 return nil
1889 },
1890 }).Run(buildTestContext(t), []string{"run", "-s", "10", "-s", "20"})
1891 }
1892
1893 func TestParseMultiFloat64SliceWithDestinationAndEnv(t *testing.T) {
1894 t.Setenv("APP_INTERVALS", "20,30,40")
1895
1896 dest := []float64{}
1897 _ = (&Command{
1898 Flags: []Flag{
1899 &FloatSliceFlag{Name: "serve", Aliases: []string{"s"}, Destination: &dest, Sources: EnvVars("APP_INTERVALS")},
1900 },
1901 Action: func(_ context.Context, cmd *Command) error {
1902 expected := []float64{10, 20}
1903 assert.Equal(t, expected, dest, "destination val not set")
1904 return nil
1905 },
1906 }).Run(buildTestContext(t), []string{"run", "-s", "10", "-s", "20"})
1907 }
1908
1909 func TestParseMultiIntSliceWithDestinationAndEnv(t *testing.T) {
1910 t.Setenv("APP_INTERVALS", "20,30,40")
1911
1912 dest := []int64{}
1913 _ = (&Command{
1914 Flags: []Flag{
1915 &Int64SliceFlag{Name: "serve", Aliases: []string{"s"}, Destination: &dest, Sources: EnvVars("APP_INTERVALS")},
1916 },
1917 Action: func(context.Context, *Command) error {
1918 require.Equalf(t, []int64{10, 20}, dest, "main name not set")
1919
1920 return nil
1921 },
1922 }).Run(buildTestContext(t), []string{"run", "-s", "10", "-s", "20"})
1923 }
1924
1925 func TestParseMultiStringSliceWithDefaultsUnset(t *testing.T) {
1926 _ = (&Command{
1927 Flags: []Flag{
1928 &StringSliceFlag{Name: "serve", Aliases: []string{"s"}, Value: []string{"9", "2"}},
1929 },
1930 Action: func(_ context.Context, cmd *Command) error {
1931 expected := []string{"9", "2"}
1932 assert.Equal(t, expected, cmd.StringSlice("serve"), "main name not set")
1933 assert.Equal(t, expected, cmd.StringSlice("s"), "short name not set")
1934 return nil
1935 },
1936 }).Run(buildTestContext(t), []string{"run"})
1937 }
1938
1939 func TestParseMultiStringSliceFromEnv(t *testing.T) {
1940 t.Setenv("APP_INTERVALS", "20,30,40")
1941
1942 _ = (&Command{
1943 Flags: []Flag{
1944 &StringSliceFlag{Name: "intervals", Aliases: []string{"i"}, Value: []string{}, Sources: EnvVars("APP_INTERVALS")},
1945 },
1946 Action: func(_ context.Context, cmd *Command) error {
1947 expected := []string{"20", "30", "40"}
1948 assert.Equal(t, expected, cmd.StringSlice("intervals"), "main name not set from env")
1949 assert.Equal(t, expected, cmd.StringSlice("i"), "short name not set from env")
1950 return nil
1951 },
1952 }).Run(buildTestContext(t), []string{"run"})
1953 }
1954
1955 func TestParseMultiStringSliceFromEnvWithDefaults(t *testing.T) {
1956 t.Setenv("APP_INTERVALS", "20,30,40")
1957
1958 _ = (&Command{
1959 Flags: []Flag{
1960 &StringSliceFlag{Name: "intervals", Aliases: []string{"i"}, Value: []string{"1", "2", "5"}, Sources: EnvVars("APP_INTERVALS")},
1961 },
1962 Action: func(_ context.Context, cmd *Command) error {
1963 expected := []string{"20", "30", "40"}
1964 assert.Equal(t, expected, cmd.StringSlice("intervals"), "main name not set from env")
1965 assert.Equal(t, expected, cmd.StringSlice("i"), "short name not set from env")
1966 return nil
1967 },
1968 }).Run(buildTestContext(t), []string{"run"})
1969 }
1970
1971 func TestParseMultiStringSliceFromEnvCascade(t *testing.T) {
1972 t.Setenv("APP_INTERVALS", "20,30,40")
1973
1974 _ = (&Command{
1975 Flags: []Flag{
1976 &StringSliceFlag{Name: "intervals", Aliases: []string{"i"}, Value: []string{}, Sources: EnvVars("COMPAT_INTERVALS", "APP_INTERVALS")},
1977 },
1978 Action: func(_ context.Context, cmd *Command) error {
1979 expected := []string{"20", "30", "40"}
1980 assert.Equal(t, expected, cmd.StringSlice("intervals"), "main name not set from env")
1981 assert.Equal(t, expected, cmd.StringSlice("i"), "short name not set from env")
1982 return nil
1983 },
1984 }).Run(buildTestContext(t), []string{"run"})
1985 }
1986
1987 func TestParseMultiStringSliceFromEnvCascadeWithDefaults(t *testing.T) {
1988 t.Setenv("APP_INTERVALS", "20,30,40")
1989
1990 _ = (&Command{
1991 Flags: []Flag{
1992 &StringSliceFlag{Name: "intervals", Aliases: []string{"i"}, Value: []string{"1", "2", "5"}, Sources: EnvVars("COMPAT_INTERVALS", "APP_INTERVALS")},
1993 },
1994 Action: func(_ context.Context, cmd *Command) error {
1995 expected := []string{"20", "30", "40"}
1996 assert.Equal(t, expected, cmd.StringSlice("intervals"), "main name not set from env")
1997 assert.Equal(t, expected, cmd.StringSlice("i"), "short name not set from env")
1998 return nil
1999 },
2000 }).Run(buildTestContext(t), []string{"run"})
2001 }
2002
2003 func TestParseMultiStringSliceFromEnvWithDestination(t *testing.T) {
2004 t.Setenv("APP_INTERVALS", "20,30,40")
2005
2006 dest := []string{}
2007 _ = (&Command{
2008 Flags: []Flag{
2009 &StringSliceFlag{Name: "intervals", Aliases: []string{"i"}, Destination: &dest, Sources: EnvVars("APP_INTERVALS")},
2010 },
2011 Action: func(context.Context, *Command) error {
2012 assert.Equal(t, []string{"20", "30", "40"}, dest, "destination value not set from env")
2013 return nil
2014 },
2015 }).Run(buildTestContext(t), []string{"run"})
2016 }
2017
2018 func TestParseMultiInt(t *testing.T) {
2019 _ = (&Command{
2020 Flags: []Flag{
2021 &Int64Flag{Name: "serve", Aliases: []string{"s"}},
2022 },
2023 Action: func(_ context.Context, cmd *Command) error {
2024 assert.Equal(t, int64(10), cmd.Int64("serve"), "main name not set")
2025 assert.Equal(t, int64(10), cmd.Int64("s"), "short name not set")
2026 return nil
2027 },
2028 }).Run(buildTestContext(t), []string{"run", "-s", "10"})
2029 }
2030
2031 func TestParseDestinationInt(t *testing.T) {
2032 var dest int64
2033 _ = (&Command{
2034 Flags: []Flag{
2035 &Int64Flag{
2036 Name: "dest",
2037 Destination: &dest,
2038 },
2039 },
2040 Action: func(context.Context, *Command) error {
2041 assert.Equal(t, int64(10), dest, "expected destination Int64 10")
2042 return nil
2043 },
2044 }).Run(buildTestContext(t), []string{"run", "--dest", "10"})
2045 }
2046
2047 func TestParseMultiIntFromEnv(t *testing.T) {
2048 t.Setenv("APP_TIMEOUT_SECONDS", "10")
2049 _ = (&Command{
2050 Flags: []Flag{
2051 &Int64Flag{Name: "timeout", Aliases: []string{"t"}, Sources: EnvVars("APP_TIMEOUT_SECONDS")},
2052 },
2053 Action: func(_ context.Context, cmd *Command) error {
2054 assert.Equal(t, int64(10), cmd.Int64("timeout"), "main name not set")
2055 assert.Equal(t, int64(10), cmd.Int64("t"), "short name not set")
2056 return nil
2057 },
2058 }).Run(buildTestContext(t), []string{"run"})
2059 }
2060
2061 func TestParseMultiIntFromEnvCascade(t *testing.T) {
2062 t.Setenv("APP_TIMEOUT_SECONDS", "10")
2063 _ = (&Command{
2064 Flags: []Flag{
2065 &Int64Flag{Name: "timeout", Aliases: []string{"t"}, Sources: EnvVars("COMPAT_TIMEOUT_SECONDS", "APP_TIMEOUT_SECONDS")},
2066 },
2067 Action: func(_ context.Context, cmd *Command) error {
2068 assert.Equal(t, int64(10), cmd.Int64("timeout"), "main name not set")
2069 assert.Equal(t, int64(10), cmd.Int64("t"), "short name not set")
2070 return nil
2071 },
2072 }).Run(buildTestContext(t), []string{"run"})
2073 }
2074
2075 func TestParseMultiIntSlice(t *testing.T) {
2076 _ = (&Command{
2077 Flags: []Flag{
2078 &Int64SliceFlag{Name: "serve", Aliases: []string{"s"}, Value: []int64{}},
2079 },
2080 Action: func(_ context.Context, cmd *Command) error {
2081 r := require.New(t)
2082
2083 r.Equalf([]int64{10, 20}, cmd.Int64Slice("serve"), "main name not set")
2084 r.Equalf([]int64{10, 20}, cmd.Int64Slice("s"), "short name not set")
2085
2086 return nil
2087 },
2088 }).Run(buildTestContext(t), []string{"run", "-s", "10", "-s", "20"})
2089 }
2090
2091 func TestParseMultiIntSliceWithDefaults(t *testing.T) {
2092 _ = (&Command{
2093 Flags: []Flag{
2094 &Int64SliceFlag{Name: "serve", Aliases: []string{"s"}, Value: []int64{9, 2}},
2095 },
2096 Action: func(_ context.Context, cmd *Command) error {
2097 r := require.New(t)
2098
2099 r.Equalf([]int64{10, 20}, cmd.Int64Slice("serve"), "main name not set")
2100 r.Equalf([]int64{10, 20}, cmd.Int64Slice("s"), "short name not set")
2101
2102 return nil
2103 },
2104 }).Run(buildTestContext(t), []string{"run", "-s", "10", "-s", "20"})
2105 }
2106
2107 func TestParseMultiIntSliceWithDefaultsUnset(t *testing.T) {
2108 _ = (&Command{
2109 Flags: []Flag{
2110 &Int64SliceFlag{Name: "serve", Aliases: []string{"s"}, Value: []int64{9, 2}},
2111 },
2112 Action: func(_ context.Context, cmd *Command) error {
2113 expected := []int64{9, 2}
2114 assert.Equal(t, expected, cmd.Int64Slice("serve"), "main name not set")
2115 assert.Equal(t, expected, cmd.Int64Slice("s"), "short name not set")
2116 return nil
2117 },
2118 }).Run(buildTestContext(t), []string{"run"})
2119 }
2120
2121 func TestParseMultiIntSliceFromEnv(t *testing.T) {
2122 t.Setenv("APP_INTERVALS", "20,30,40")
2123
2124 _ = (&Command{
2125 Flags: []Flag{
2126 &Int64SliceFlag{Name: "intervals", Aliases: []string{"i"}, Value: []int64{}, Sources: EnvVars("APP_INTERVALS")},
2127 },
2128 Action: func(_ context.Context, cmd *Command) error {
2129 r := require.New(t)
2130
2131 r.Equalf([]int64{20, 30, 40}, cmd.Int64Slice("intervals"), "main name not set from env")
2132 r.Equalf([]int64{20, 30, 40}, cmd.Int64Slice("i"), "short name not set from env")
2133
2134 return nil
2135 },
2136 }).Run(buildTestContext(t), []string{"run"})
2137 }
2138
2139 func TestParseMultiIntSliceFromEnvWithDefaults(t *testing.T) {
2140 t.Setenv("APP_INTERVALS", "20,30,40")
2141
2142 _ = (&Command{
2143 Flags: []Flag{
2144 &Int64SliceFlag{Name: "intervals", Aliases: []string{"i"}, Value: []int64{1, 2, 5}, Sources: EnvVars("APP_INTERVALS")},
2145 },
2146 Action: func(_ context.Context, cmd *Command) error {
2147 r := require.New(t)
2148
2149 r.Equalf([]int64{20, 30, 40}, cmd.Int64Slice("intervals"), "main name not set from env")
2150 r.Equalf([]int64{20, 30, 40}, cmd.Int64Slice("i"), "short name not set from env")
2151 return nil
2152 },
2153 }).Run(buildTestContext(t), []string{"run"})
2154 }
2155
2156 func TestParseMultiIntSliceFromEnvCascade(t *testing.T) {
2157 t.Setenv("APP_INTERVALS", "20,30,40")
2158
2159 _ = (&Command{
2160 Flags: []Flag{
2161 &Int64SliceFlag{Name: "intervals", Aliases: []string{"i"}, Value: []int64{}, Sources: EnvVars("COMPAT_INTERVALS", "APP_INTERVALS")},
2162 },
2163 Action: func(_ context.Context, cmd *Command) error {
2164 r := require.New(t)
2165
2166 r.Equalf([]int64{20, 30, 40}, cmd.Int64Slice("intervals"), "main name not set from env")
2167 r.Equalf([]int64{20, 30, 40}, cmd.Int64Slice("i"), "short name not set from env")
2168
2169 return nil
2170 },
2171 }).Run(buildTestContext(t), []string{"run"})
2172 }
2173
2174 func TestParseMultiFloat64(t *testing.T) {
2175 _ = (&Command{
2176 Flags: []Flag{
2177 &FloatFlag{Name: "serve", Aliases: []string{"s"}},
2178 },
2179 Action: func(_ context.Context, cmd *Command) error {
2180 assert.Equal(t, 10.2, cmd.Float("serve"), "main name not set")
2181 assert.Equal(t, 10.2, cmd.Float("s"), "short name not set")
2182 return nil
2183 },
2184 }).Run(buildTestContext(t), []string{"run", "-s", "10.2"})
2185 }
2186
2187 func TestParseDestinationFloat64(t *testing.T) {
2188 var dest float64
2189 _ = (&Command{
2190 Flags: []Flag{
2191 &FloatFlag{
2192 Name: "dest",
2193 Destination: &dest,
2194 },
2195 },
2196 Action: func(context.Context, *Command) error {
2197 assert.Equal(t, 10.2, dest, "expected destination Float64 10.2")
2198 return nil
2199 },
2200 }).Run(buildTestContext(t), []string{"run", "--dest", "10.2"})
2201 }
2202
2203 func TestParseMultiFloat64FromEnv(t *testing.T) {
2204 t.Setenv("APP_TIMEOUT_SECONDS", "15.5")
2205 _ = (&Command{
2206 Flags: []Flag{
2207 &FloatFlag{Name: "timeout", Aliases: []string{"t"}, Sources: EnvVars("APP_TIMEOUT_SECONDS")},
2208 },
2209 Action: func(_ context.Context, cmd *Command) error {
2210 assert.Equal(t, 15.5, cmd.Float("timeout"), "main name not set")
2211 assert.Equal(t, 15.5, cmd.Float("t"), "short name not set")
2212 return nil
2213 },
2214 }).Run(buildTestContext(t), []string{"run"})
2215 }
2216
2217 func TestParseMultiFloat64FromEnvCascade(t *testing.T) {
2218 t.Setenv("APP_TIMEOUT_SECONDS", "15.5")
2219
2220 _ = (&Command{
2221 Flags: []Flag{
2222 &FloatFlag{Name: "timeout", Aliases: []string{"t"}, Sources: EnvVars("COMPAT_TIMEOUT_SECONDS", "APP_TIMEOUT_SECONDS")},
2223 },
2224 Action: func(_ context.Context, cmd *Command) error {
2225 assert.Equal(t, 15.5, cmd.Float("timeout"), "main name not set")
2226 assert.Equal(t, 15.5, cmd.Float("t"), "short name not set")
2227 return nil
2228 },
2229 }).Run(buildTestContext(t), []string{"run"})
2230 }
2231
2232 func TestParseMultiFloat64SliceFromEnv(t *testing.T) {
2233 t.Setenv("APP_INTERVALS", "0.1,-10.5")
2234
2235 _ = (&Command{
2236 Flags: []Flag{
2237 &FloatSliceFlag{Name: "intervals", Aliases: []string{"i"}, Value: []float64{}, Sources: EnvVars("APP_INTERVALS")},
2238 },
2239 Action: func(_ context.Context, cmd *Command) error {
2240 require.Equalf(t, []float64{0.1, -10.5}, cmd.FloatSlice("intervals"), "main name not set from env")
2241 return nil
2242 },
2243 }).Run(buildTestContext(t), []string{"run"})
2244 }
2245
2246 func TestParseMultiFloat64SliceFromEnvCascade(t *testing.T) {
2247 t.Setenv("APP_INTERVALS", "0.1234,-10.5")
2248
2249 _ = (&Command{
2250 Flags: []Flag{
2251 &FloatSliceFlag{Name: "intervals", Aliases: []string{"i"}, Value: []float64{}, Sources: EnvVars("COMPAT_INTERVALS", "APP_INTERVALS")},
2252 },
2253 Action: func(_ context.Context, cmd *Command) error {
2254 require.Equalf(t, []float64{0.1234, -10.5}, cmd.FloatSlice("intervals"), "main name not set from env")
2255 return nil
2256 },
2257 }).Run(buildTestContext(t), []string{"run"})
2258 }
2259
2260 func TestParseMultiBool(t *testing.T) {
2261 _ = (&Command{
2262 Flags: []Flag{
2263 &BoolFlag{Name: "serve", Aliases: []string{"s"}},
2264 },
2265 Action: func(_ context.Context, cmd *Command) error {
2266 assert.True(t, cmd.Bool("serve"), "main name not set")
2267 assert.True(t, cmd.Bool("s"), "short name not set")
2268 return nil
2269 },
2270 }).Run(buildTestContext(t), []string{"run", "--serve"})
2271 }
2272
2273 func TestParseBoolShortOptionHandle(t *testing.T) {
2274 _ = (&Command{
2275 Commands: []*Command{
2276 {
2277 Name: "foobar",
2278 UseShortOptionHandling: true,
2279 Action: func(_ context.Context, cmd *Command) error {
2280 assert.True(t, cmd.Bool("serve"), "main name not set")
2281 assert.True(t, cmd.Bool("option"), "short name not set")
2282 return nil
2283 },
2284 Flags: []Flag{
2285 &BoolFlag{Name: "serve", Aliases: []string{"s"}},
2286 &BoolFlag{Name: "option", Aliases: []string{"o"}},
2287 },
2288 },
2289 },
2290 }).Run(buildTestContext(t), []string{"run", "foobar", "-so"})
2291 }
2292
2293 func TestParseDestinationBool(t *testing.T) {
2294 var dest bool
2295 _ = (&Command{
2296 Flags: []Flag{
2297 &BoolFlag{
2298 Name: "dest",
2299 Destination: &dest,
2300 },
2301 },
2302 Action: func(context.Context, *Command) error {
2303 assert.True(t, dest, "expected destination Bool true")
2304 return nil
2305 },
2306 }).Run(buildTestContext(t), []string{"run", "--dest"})
2307 }
2308
2309 func TestParseMultiBoolFromEnv(t *testing.T) {
2310 t.Setenv("APP_DEBUG", "1")
2311 _ = (&Command{
2312 Flags: []Flag{
2313 &BoolFlag{Name: "debug", Aliases: []string{"d"}, Sources: EnvVars("APP_DEBUG")},
2314 },
2315 Action: func(_ context.Context, cmd *Command) error {
2316 assert.True(t, cmd.Bool("debug"), "main name not set")
2317 assert.True(t, cmd.Bool("d"), "short name not set")
2318 return nil
2319 },
2320 }).Run(buildTestContext(t), []string{"run"})
2321 }
2322
2323 func TestParseMultiBoolFromEnvCascade(t *testing.T) {
2324 t.Setenv("APP_DEBUG", "1")
2325 _ = (&Command{
2326 Flags: []Flag{
2327 &BoolFlag{Name: "debug", Aliases: []string{"d"}, Sources: EnvVars("COMPAT_DEBUG", "APP_DEBUG")},
2328 },
2329 Action: func(_ context.Context, cmd *Command) error {
2330 assert.True(t, cmd.Bool("debug"), "main name not set from env")
2331 assert.True(t, cmd.Bool("d"), "short name not set from env")
2332 return nil
2333 },
2334 }).Run(buildTestContext(t), []string{"run"})
2335 }
2336
2337 func TestParseBoolFromEnv(t *testing.T) {
2338 boolFlagTests := []struct {
2339 input string
2340 output bool
2341 }{
2342 {"", false},
2343 {"1", true},
2344 {"false", false},
2345 {"true", true},
2346 }
2347
2348 for _, test := range boolFlagTests {
2349 t.Run(fmt.Sprintf("%[1]q %[2]v", test.input, test.output), func(t *testing.T) {
2350 t.Setenv("DEBUG", test.input)
2351 _ = (&Command{
2352 Flags: []Flag{
2353 &BoolFlag{Name: "debug", Aliases: []string{"d"}, Sources: EnvVars("DEBUG")},
2354 },
2355 Action: func(_ context.Context, cmd *Command) error {
2356 assert.Equal(t, test.output, cmd.Bool("debug"))
2357 assert.Equal(t, test.output, cmd.Bool("d"))
2358 return nil
2359 },
2360 }).Run(buildTestContext(t), []string{"run"})
2361 })
2362 }
2363 }
2364
2365 func TestParseMultiBoolT(t *testing.T) {
2366 _ = (&Command{
2367 Flags: []Flag{
2368 &BoolFlag{Name: "implode", Aliases: []string{"i"}, Value: true},
2369 },
2370 Action: func(_ context.Context, cmd *Command) error {
2371 assert.False(t, cmd.Bool("implode"), "main name not set")
2372 assert.False(t, cmd.Bool("i"), "short name not set")
2373 return nil
2374 },
2375 }).Run(buildTestContext(t), []string{"run", "--implode=false"})
2376 }
2377
2378 func TestStringSliceFlagApply_LocalPreservesRepeatedValues(t *testing.T) {
2379 var got []string
2380 cmd := &Command{
2381 Flags: []Flag{
2382 &StringSliceFlag{Name: "values", Local: true},
2383 },
2384 Action: func(_ context.Context, cmd *Command) error {
2385 got = cmd.StringSlice("values")
2386 return nil
2387 },
2388 }
2389
2390 require.NoError(t, cmd.Run(buildTestContext(t), []string{"run", "--values", "a,b,c", "--values", "d", "--values", "e"}))
2391 require.Equal(t, []string{"a", "b", "c", "d", "e"}, got)
2392 }
2393
2394 func TestStringSlice_Serialized_Set(t *testing.T) {
2395 sl0 := NewStringSlice("a", "b")
2396 ser0 := sl0.Serialize()
2397
2398 require.GreaterOrEqual(t, len(ser0), len(slPfx), "serialized shorter than expected")
2399
2400 sl1 := NewStringSlice("c", "d")
2401 _ = sl1.Set(ser0)
2402
2403 require.Equal(t, sl0.String(), sl1.String(), "pre and post serialization do not match")
2404 }
2405
2406 func TestIntSlice_Serialized_Set(t *testing.T) {
2407 sl0 := NewInt64Slice(1, 2)
2408 ser0 := sl0.Serialize()
2409
2410 require.GreaterOrEqual(t, len(ser0), len(slPfx), "serialized shorter than expected")
2411
2412 sl1 := NewInt64Slice(3, 4)
2413 _ = sl1.Set(ser0)
2414
2415 require.Equal(t, sl0.String(), sl1.String(), "pre and post serialization do not match")
2416 }
2417
2418 func TestUintSlice_Serialized_Set(t *testing.T) {
2419 sl0 := NewUint64Slice(1, 2)
2420 ser0 := sl0.Serialize()
2421
2422 require.GreaterOrEqual(t, len(ser0), len(slPfx), "serialized shorter than expected")
2423
2424 sl1 := NewUint64Slice(3, 4)
2425 _ = sl1.Set(ser0)
2426
2427 require.Equal(t, sl0.String(), sl1.String(), "pre and post serialization do not match")
2428 }
2429
2430 func TestUint64Slice_Serialized_Set(t *testing.T) {
2431 sl0 := NewUint64Slice(1, 2)
2432 ser0 := sl0.Serialize()
2433
2434 require.GreaterOrEqual(t, len(ser0), len(slPfx), "serialized shorter than expected")
2435
2436 sl1 := NewUint64Slice(3, 4)
2437 _ = sl1.Set(ser0)
2438
2439 require.Equal(t, sl0.String(), sl1.String(), "pre and post serialization do not match")
2440 }
2441
2442 func TestStringMap_Serialized_Set(t *testing.T) {
2443 m0 := NewStringMap(map[string]string{"a": "b"})
2444 ser0 := m0.Serialize()
2445
2446 require.GreaterOrEqual(t, len(ser0), len(slPfx), "serialized shorter than expected")
2447
2448 m1 := NewStringMap(map[string]string{"c": "d"})
2449 _ = m1.Set(ser0)
2450
2451 require.Equal(t, m0.String(), m1.String(), "pre and post serialization do not match")
2452 }
2453
2454 var timestampFlagTests = []struct {
2455 name string
2456 aliases []string
2457 usage string
2458 expected string
2459 }{
2460 {"foo", nil, "", "--foo time\t(default: 2020-04-10 01:01:01.000000001 +0000 UTC)"},
2461 {"f", nil, "all", "-f time\tall (default: 2020-04-10 01:01:01.000000001 +0000 UTC)"},
2462 }
2463
2464 func TestTimestampFlagHelpOutput(t *testing.T) {
2465 tl, err := time.LoadLocation("UTC")
2466 assert.NoError(t, err)
2467 for _, test := range timestampFlagTests {
2468 value := time.Date(2020, time.April, 10, 1, 1, 1, 1, tl)
2469 fl := &TimestampFlag{Name: test.name, Aliases: test.aliases, Usage: test.usage, Value: value}
2470 assert.Equal(t, test.expected, fl.String())
2471 }
2472 }
2473
2474 func TestTimestamp_set(t *testing.T) {
2475 ts := timestampValue{
2476 timestamp: nil,
2477 hasBeenSet: false,
2478 layouts: []string{"Jan 2, 2006 at 3:04pm (MST)"},
2479 }
2480
2481 time1 := "Feb 3, 2013 at 7:54pm (PST)"
2482 require.NoError(t, ts.Set(time1), "Failed to parse time %s with layouts %v", time1, ts.layouts)
2483 require.True(t, ts.hasBeenSet, "hasBeenSet is not true after setting a time")
2484
2485 ts.hasBeenSet = false
2486 ts.layouts = []string{time.RFC3339}
2487 time2 := "2006-01-02T15:04:05Z"
2488 require.NoError(t, ts.Set(time2), "Failed to parse time %s with layout %v", time2, ts.layouts)
2489 require.True(t, ts.hasBeenSet, "hasBeenSet is not true after setting a time")
2490 }
2491
2492 func TestTimestampFlagApply_SingleFormat(t *testing.T) {
2493 expectedResult, _ := time.Parse(time.RFC3339, "2006-01-02T15:04:05Z")
2494 fl := TimestampFlag{Name: "time", Aliases: []string{"t"}, Config: TimestampConfig{Layouts: []string{time.RFC3339}}}
2495 cmd := &Command{
2496 Flags: []Flag{
2497 &fl,
2498 },
2499 }
2500
2501 assert.NoError(t, cmd.Run(buildTestContext(t), []string{"", "--time", "2006-01-02T15:04:05Z"}))
2502 assert.Equal(t, expectedResult, cmd.Value("time"))
2503 }
2504
2505 func TestTimestampFlagApply_MultipleFormats(t *testing.T) {
2506 now := time.Now().UTC()
2507
2508 testCases := []struct {
2509 caseName string
2510 layoutsPrecisions map[string]time.Duration
2511 expRes time.Time
2512 expErrValidation func(err error) (validation error)
2513 }{
2514 {
2515 caseName: "all_valid_layouts",
2516 layoutsPrecisions: map[string]time.Duration{
2517 time.RFC3339: time.Second,
2518 time.DateTime: time.Second,
2519 time.RFC1123: time.Second,
2520 },
2521 expRes: now.Truncate(time.Second),
2522 },
2523 {
2524 caseName: "one_invalid_layout",
2525 layoutsPrecisions: map[string]time.Duration{
2526 time.RFC3339: time.Second,
2527 time.DateTime: time.Second,
2528 "foo": 0,
2529 },
2530 expRes: now.Truncate(time.Second),
2531 },
2532 {
2533 caseName: "multiple_invalid_layouts",
2534 layoutsPrecisions: map[string]time.Duration{
2535 time.RFC3339: time.Second,
2536 "foo": 0,
2537 time.DateTime: time.Second,
2538 "bar": 0,
2539 },
2540 expRes: now.Truncate(time.Second),
2541 },
2542 {
2543 caseName: "all_invalid_layouts",
2544 layoutsPrecisions: map[string]time.Duration{
2545 "foo": 0,
2546 "2024-08-07 74:01:82Z-100": 0,
2547 "25:70": 0,
2548 "": 0,
2549 },
2550 expErrValidation: func(err error) error {
2551 if err == nil {
2552 return errors.New("got nil err")
2553 }
2554
2555 found := regexp.MustCompile(`(cannot parse ".+" as ".*")|(extra text: ".+")`).Match([]byte(err.Error()))
2556 if !found {
2557 return fmt.Errorf("given error does not satisfy pattern: %w", err)
2558 }
2559
2560 return nil
2561 },
2562 },
2563 {
2564 caseName: "empty_layout",
2565 layoutsPrecisions: map[string]time.Duration{
2566 "": 0,
2567 },
2568 expErrValidation: func(err error) error {
2569 if err == nil {
2570 return errors.New("got nil err")
2571 }
2572
2573 found := regexp.MustCompile(`extra text: ".+"`).Match([]byte(err.Error()))
2574 if !found {
2575 return fmt.Errorf("given error does not satisfy pattern: %w", err)
2576 }
2577
2578 return nil
2579 },
2580 },
2581 {
2582 caseName: "nil_layouts_slice",
2583 expErrValidation: func(err error) error {
2584 if err == nil {
2585 return errors.New("got nil err")
2586 }
2587
2588 found := regexp.MustCompile(`got nil/empty layouts slice`).Match([]byte(err.Error()))
2589 if !found {
2590 return fmt.Errorf("given error does not satisfy pattern: %w", err)
2591 }
2592
2593 return nil
2594 },
2595 },
2596 {
2597 caseName: "empty_layouts_slice",
2598 layoutsPrecisions: map[string]time.Duration{},
2599 expErrValidation: func(err error) error {
2600 if err == nil {
2601 return errors.New("got nil err")
2602 }
2603
2604 found := regexp.MustCompile(`got nil/empty layouts slice`).Match([]byte(err.Error()))
2605 if !found {
2606 return fmt.Errorf("given error does not satisfy pattern: %w", err)
2607 }
2608
2609 return nil
2610 },
2611 },
2612 }
2613
2614 // TODO: replace with maps.Keys() (go >= ), lo.Keys() if acceptable
2615 getKeys := func(m map[string]time.Duration) []string {
2616 if m == nil {
2617 return nil
2618 }
2619
2620 keys := make([]string, 0, len(m))
2621 for k := range m {
2622 keys = append(keys, k)
2623 }
2624 return keys
2625 }
2626
2627 for idx := range testCases {
2628 testCase := testCases[idx]
2629 t.Run(testCase.caseName, func(t *testing.T) {
2630 // t.Parallel()
2631 fl := TimestampFlag{
2632 Name: "time",
2633 Config: TimestampConfig{
2634 Layouts: getKeys(testCase.layoutsPrecisions),
2635 },
2636 }
2637
2638 if len(testCase.layoutsPrecisions) == 0 {
2639 err := fl.Set(fl.Name, now.Format(time.RFC3339))
2640 if testCase.expErrValidation != nil {
2641 assert.NoError(t, testCase.expErrValidation(err))
2642 }
2643 }
2644
2645 validLayouts := make([]string, 0, len(testCase.layoutsPrecisions))
2646 invalidLayouts := make([]string, 0, len(testCase.layoutsPrecisions))
2647
2648 // TODO: replace with lo.Filter if acceptable
2649 for layout, prec := range testCase.layoutsPrecisions {
2650 v, err := time.Parse(layout, now.Format(layout))
2651 if err != nil || prec == 0 || now.Truncate(prec).UnixNano() != v.Truncate(prec).UnixNano() {
2652 invalidLayouts = append(invalidLayouts, layout)
2653 continue
2654 }
2655 validLayouts = append(validLayouts, layout)
2656 }
2657
2658 for _, layout := range validLayouts {
2659 err := fl.Set(fl.Name, now.Format(layout))
2660 assert.NoError(t, err)
2661 if !testCase.expRes.IsZero() {
2662 assert.Equal(t, testCase.expRes, fl.value.Get())
2663 }
2664 }
2665
2666 for range invalidLayouts {
2667 err := fl.Set(fl.Name, now.Format(time.RFC3339))
2668 if testCase.expErrValidation != nil {
2669 assert.NoError(t, testCase.expErrValidation(err))
2670 }
2671 }
2672 })
2673 }
2674 }
2675
2676 func TestTimestampFlagApply_ShortenedLayouts(t *testing.T) {
2677 now := time.Now().UTC()
2678
2679 shortenedLayoutsPrecisions := map[string]time.Duration{
2680 time.Kitchen: time.Minute,
2681 time.Stamp: time.Second,
2682 time.StampMilli: time.Millisecond,
2683 time.StampMicro: time.Microsecond,
2684 time.StampNano: time.Nanosecond,
2685 time.TimeOnly: time.Second,
2686 "15:04": time.Minute,
2687 }
2688
2689 // TODO: replace with maps.Keys() (go >= ), lo.Keys() if acceptable
2690 getKeys := func(m map[string]time.Duration) []string {
2691 if m == nil {
2692 return nil
2693 }
2694
2695 keys := make([]string, 0, len(m))
2696 for k := range m {
2697 keys = append(keys, k)
2698 }
2699 return keys
2700 }
2701
2702 fl := TimestampFlag{
2703 Name: "time",
2704 Config: TimestampConfig{
2705 Layouts: getKeys(shortenedLayoutsPrecisions),
2706 },
2707 }
2708
2709 for layout, prec := range shortenedLayoutsPrecisions {
2710 err := fl.Set(fl.Name, now.Format(layout))
2711 assert.NoError(t, err)
2712 assert.Equal(t, now.Truncate(prec), fl.value.Get())
2713 }
2714 }
2715
2716 func TestTimestampFlagApplyValue(t *testing.T) {
2717 expectedResult, _ := time.Parse(time.RFC3339, "2006-01-02T15:04:05Z")
2718 fl := TimestampFlag{Name: "time", Aliases: []string{"t"}, Config: TimestampConfig{Layouts: []string{time.RFC3339}}, Value: expectedResult}
2719 cmd := &Command{
2720 Flags: []Flag{
2721 &fl,
2722 },
2723 }
2724
2725 assert.NoError(t, cmd.Run(buildTestContext(t), []string{""}))
2726 assert.Equal(t, expectedResult, cmd.Value("time"))
2727 }
2728
2729 func TestTimestampFlagApply_Fail_Parse_Wrong_Layout(t *testing.T) {
2730 fl := TimestampFlag{Name: "time", Aliases: []string{"t"}, Config: TimestampConfig{Layouts: []string{"randomlayout"}}}
2731 cmd := &Command{
2732 Flags: []Flag{
2733 &fl,
2734 },
2735 }
2736
2737 err := cmd.Run(buildTestContext(t), []string{"", "--time", "2006-01-02T15:04:05Z"})
2738 assert.EqualError(t, err, "invalid value \"2006-01-02T15:04:05Z\" for flag -time: parsing time \"2006-01-02T15:04:05Z\" as \"randomlayout\": cannot parse \"2006-01-02T15:04:05Z\" as \"randomlayout\"")
2739 }
2740
2741 func TestTimestampFlagApply_Fail_Parse_Wrong_Time(t *testing.T) {
2742 fl := TimestampFlag{Name: "time", Aliases: []string{"t"}, Config: TimestampConfig{Layouts: []string{"Jan 2, 2006 at 3:04pm (MST)"}}}
2743 cmd := &Command{
2744 Flags: []Flag{
2745 &fl,
2746 },
2747 }
2748 err := cmd.Set("time", "2006-01-02T15:04:05Z")
2749 assert.EqualError(t, err, "parsing time \"2006-01-02T15:04:05Z\" as \"Jan 2, 2006 at 3:04pm (MST)\": cannot parse \"2006-01-02T15:04:05Z\" as \"Jan\"")
2750 }
2751
2752 func TestTimestampFlagApply_Timezoned(t *testing.T) {
2753 pdt := time.FixedZone("PDT", -7*60*60)
2754 expectedResult, _ := time.Parse(time.RFC3339, "2006-01-02T15:04:05Z")
2755 fl := TimestampFlag{Name: "time", Aliases: []string{"t"}, Config: TimestampConfig{Layouts: []string{time.ANSIC}, Timezone: pdt}}
2756 cmd := &Command{
2757 Flags: []Flag{
2758 &fl,
2759 },
2760 }
2761
2762 assert.NoError(t, cmd.Run(buildTestContext(t), []string{"", "--time", "Mon Jan 2 08:04:05 2006"}))
2763 assert.Equal(t, expectedResult.In(pdt), cmd.Value("time"))
2764 }
2765
2766 func TestTimestampFlagValueFromCommand(t *testing.T) {
2767 now := time.Now()
2768 cmd := &Command{
2769 Flags: []Flag{
2770 &TimestampFlag{
2771 Name: "myflag",
2772 Value: now,
2773 },
2774 },
2775 }
2776 f := &TimestampFlag{Name: "myflag"}
2777 require.Equal(t, now, cmd.Timestamp(f.Name))
2778 }
2779
2780 type flagDefaultTestCase struct {
2781 name string
2782 flag Flag
2783 toParse []string
2784 expect string
2785 }
2786
2787 func TestFlagDefaultValue(t *testing.T) {
2788 cases := []*flagDefaultTestCase{
2789 {
2790 name: "stringSlice",
2791 flag: &StringSliceFlag{Name: "flag", Value: []string{"default1", "default2"}},
2792 toParse: []string{"--flag", "parsed"},
2793 expect: `--flag string [ --flag string ] (default: "default1", "default2")`,
2794 },
2795 {
2796 name: "floatSlice",
2797 flag: &FloatSliceFlag{Name: "flag", Value: []float64{1.1, 2.2}},
2798 toParse: []string{"--flag", "13.3"},
2799 expect: `--flag float [ --flag float ] (default: 1.1, 2.2)`,
2800 },
2801 {
2802 name: "float32Slice",
2803 flag: &Float32SliceFlag{Name: "flag", Value: []float32{1.1, 2.2}},
2804 toParse: []string{"--flag", "13.3"},
2805 expect: `--flag float [ --flag float ] (default: 1.1, 2.2)`,
2806 },
2807 {
2808 name: "float64Slice",
2809 flag: &Float64SliceFlag{Name: "flag", Value: []float64{1.1, 2.2}},
2810 toParse: []string{"--flag", "13.3"},
2811 expect: `--flag float [ --flag float ] (default: 1.1, 2.2)`,
2812 },
2813 {
2814 name: "intSlice",
2815 flag: &Int64SliceFlag{Name: "flag", Value: []int64{1, 2}},
2816 toParse: []string{"--flag", "13"},
2817 expect: `--flag int [ --flag int ] (default: 1, 2)`,
2818 },
2819 {
2820 name: "uintSlice",
2821 flag: &Uint64SliceFlag{Name: "flag", Value: []uint64{1, 2}},
2822 toParse: []string{"--flag", "13"},
2823 expect: `--flag uint [ --flag uint ] (default: 1, 2)`,
2824 },
2825 {
2826 name: "string",
2827 flag: &StringFlag{Name: "flag", Value: "default"},
2828 toParse: []string{"--flag", "parsed"},
2829 expect: `--flag string (default: "default")`,
2830 },
2831 {
2832 name: "bool",
2833 flag: &BoolFlag{Name: "flag", Value: true},
2834 toParse: []string{"--flag=false"},
2835 expect: `--flag `,
2836 },
2837 {
2838 name: "uint",
2839 flag: &UintFlag{Name: "flag", Value: 1},
2840 toParse: []string{"--flag", "13"},
2841 expect: `--flag uint (default: 1)`,
2842 },
2843 {
2844 name: "uint64",
2845 flag: &Uint64Flag{Name: "flag", Value: 1},
2846 toParse: []string{"--flag", "13"},
2847 expect: `--flag uint (default: 1)`,
2848 },
2849 {
2850 name: "stringMap",
2851 flag: &StringMapFlag{Name: "flag", Value: map[string]string{"default1": "default2"}},
2852 toParse: []string{"--flag", "parsed="},
2853 expect: `--flag string=string [ --flag string=string ] (default: default1="default2")`,
2854 },
2855 }
2856 for _, v := range cases {
2857 t.Run(v.name, func(t *testing.T) {
2858 cmd := &Command{
2859 Flags: []Flag{
2860 v.flag,
2861 },
2862 }
2863 assert.NoError(t, cmd.Run(buildTestContext(t), append([]string{""}, v.toParse...)))
2864 assert.Equal(t, v.expect, v.flag.String())
2865 })
2866 }
2867 }
2868
2869 type flagDefaultTestCaseWithEnv struct {
2870 name string
2871 flag Flag
2872 toParse []string
2873 expect string
2874 environ map[string]string
2875 }
2876
2877 func TestFlagDefaultValueWithEnv(t *testing.T) {
2878 ts, err := time.Parse(time.RFC3339, "2005-01-02T15:04:05Z")
2879 require.NoError(t, err)
2880 cases := []*flagDefaultTestCaseWithEnv{
2881 {
2882 name: "stringSlice",
2883 flag: &StringSliceFlag{Name: "flag", Value: []string{"default1", "default2"}, Sources: EnvVars("ssflag")},
2884 toParse: []string{"--flag", "parsed"},
2885 expect: `--flag string [ --flag string ] (default: "default1", "default2")` + withEnvHint([]string{"ssflag"}, ""),
2886 environ: map[string]string{
2887 "ssflag": "some-other-env_value",
2888 },
2889 },
2890 {
2891 name: "float64Slice",
2892 flag: &FloatSliceFlag{Name: "flag", Value: []float64{1.1, 2.2}, Sources: EnvVars("fsflag")},
2893 toParse: []string{"--flag", "13.3"},
2894 expect: `--flag float [ --flag float ] (default: 1.1, 2.2)` + withEnvHint([]string{"fsflag"}, ""),
2895 environ: map[string]string{
2896 "fsflag": "20304.222",
2897 },
2898 },
2899 {
2900 name: "intSlice",
2901 flag: &Int64SliceFlag{Name: "flag", Value: []int64{1, 2}, Sources: EnvVars("isflag")},
2902 toParse: []string{"--flag", "13"},
2903 expect: `--flag int [ --flag int ] (default: 1, 2)` + withEnvHint([]string{"isflag"}, ""),
2904 environ: map[string]string{
2905 "isflag": "101",
2906 },
2907 },
2908 {
2909 name: "uintSlice",
2910 flag: &Uint64SliceFlag{Name: "flag", Value: []uint64{1, 2}, Sources: EnvVars("uisflag")},
2911 toParse: []string{"--flag", "13"},
2912 expect: `--flag uint [ --flag uint ] (default: 1, 2)` + withEnvHint([]string{"uisflag"}, ""),
2913 environ: map[string]string{
2914 "uisflag": "3",
2915 },
2916 },
2917 {
2918 name: "string",
2919 flag: &StringFlag{Name: "flag", Value: "default", Sources: EnvVars("uflag")},
2920 toParse: []string{"--flag", "parsed"},
2921 expect: `--flag string (default: "default")` + withEnvHint([]string{"uflag"}, ""),
2922 environ: map[string]string{
2923 "uflag": "some-other-string",
2924 },
2925 },
2926 {
2927 name: "bool",
2928 flag: &BoolFlag{Name: "flag", Value: true, Sources: EnvVars("uflag")},
2929 toParse: []string{"--flag=false"},
2930 expect: `--flag ` + withEnvHint([]string{"uflag"}, ""),
2931 environ: map[string]string{
2932 "uflag": "false",
2933 },
2934 },
2935 {
2936 name: "bool",
2937 flag: &BoolWithInverseFlag{Name: "flag", Value: true, Sources: EnvVars("uflag")},
2938 expect: `--[no-]flag (default: true)` + withEnvHint([]string{"uflag"}, ""),
2939 environ: map[string]string{
2940 "uflag": "false",
2941 },
2942 },
2943 {
2944 name: "uint64",
2945 flag: &Uint64Flag{Name: "flag", Value: 1, Sources: EnvVars("uflag")},
2946 toParse: []string{"--flag", "13"},
2947 expect: `--flag uint (default: 1)` + withEnvHint([]string{"uflag"}, ""),
2948 environ: map[string]string{
2949 "uflag": "10",
2950 },
2951 },
2952 {
2953 name: "uint",
2954 flag: &Uint64Flag{Name: "flag", Value: 1, Sources: EnvVars("uflag")},
2955 toParse: []string{"--flag", "13"},
2956 expect: `--flag uint (default: 1)` + withEnvHint([]string{"uflag"}, ""),
2957 environ: map[string]string{
2958 "uflag": "10",
2959 },
2960 },
2961 {
2962 name: "int64",
2963 flag: &Int64Flag{Name: "flag", Value: 1, Sources: EnvVars("uflag")},
2964 toParse: []string{"--flag", "13"},
2965 expect: `--flag int (default: 1)` + withEnvHint([]string{"uflag"}, ""),
2966 environ: map[string]string{
2967 "uflag": "10",
2968 },
2969 },
2970 {
2971 name: "int",
2972 flag: &Int64Flag{Name: "flag", Value: 1, Sources: EnvVars("uflag")},
2973 toParse: []string{"--flag", "13"},
2974 expect: `--flag int (default: 1)` + withEnvHint([]string{"uflag"}, ""),
2975 environ: map[string]string{
2976 "uflag": "10",
2977 },
2978 },
2979 {
2980 name: "duration",
2981 flag: &DurationFlag{Name: "flag", Value: time.Second, Sources: EnvVars("uflag")},
2982 toParse: []string{"--flag", "2m"},
2983 expect: `--flag duration (default: 1s)` + withEnvHint([]string{"uflag"}, ""),
2984 environ: map[string]string{
2985 "uflag": "2h4m10s",
2986 },
2987 },
2988 {
2989 name: "timestamp",
2990 flag: &TimestampFlag{Name: "flag", Value: ts, Config: TimestampConfig{Layouts: []string{time.RFC3339}}, Sources: EnvVars("tflag")},
2991 toParse: []string{"--flag", "2006-11-02T15:04:05Z"},
2992 expect: `--flag time (default: 2005-01-02 15:04:05 +0000 UTC)` + withEnvHint([]string{"tflag"}, ""),
2993 environ: map[string]string{
2994 "tflag": "2010-01-02T15:04:05Z",
2995 },
2996 },
2997 {
2998 name: "stringMap",
2999 flag: &StringMapFlag{Name: "flag", Value: map[string]string{"default1": "default2"}, Sources: EnvVars("ssflag")},
3000 toParse: []string{"--flag", "parsed="},
3001 expect: `--flag string=string [ --flag string=string ] (default: default1="default2")` + withEnvHint([]string{"ssflag"}, ""),
3002 environ: map[string]string{
3003 "ssflag": "some-other-env_value=",
3004 },
3005 },
3006 // TODO
3007 /*{
3008 name: "generic",
3009 flag: &GenericFlag{Name: "flag", Value: &Parser{"11", "12"}, Sources: EnvVars("gflag")},
3010 toParse: []string{"--flag", "15,16"},
3011 expect: `--flag value (default: 11,12)` + withEnvHint([]string{"gflag"}, ""),
3012 environ: map[string]string{
3013 "gflag": "13,14",
3014 },
3015 },*/
3016 }
3017 for _, v := range cases {
3018 t.Run(v.name, func(t *testing.T) {
3019 for key, val := range v.environ {
3020 t.Setenv(key, val)
3021 }
3022 cmd := &Command{
3023 Flags: []Flag{
3024 v.flag,
3025 },
3026 }
3027 require.NoError(t, cmd.Run(buildTestContext(t), append([]string{""}, v.toParse...)))
3028 assert.Equal(t, v.expect, v.flag.String())
3029 })
3030 }
3031 }
3032
3033 type flagValueTestCase struct {
3034 name string
3035 flag Flag
3036 toParse []string
3037 expect string
3038 }
3039
3040 func TestFlagValue(t *testing.T) {
3041 t.SkipNow()
3042 cases := []*flagValueTestCase{
3043 {
3044 name: "stringSlice",
3045 flag: &StringSliceFlag{Name: "flag", Value: []string{"default1", "default2"}},
3046 toParse: []string{"--flag", "parsed,parsed2", "--flag", "parsed3,parsed4"},
3047 expect: `[parsed parsed2 parsed3 parsed4]`,
3048 },
3049 {
3050 name: "float64Slice",
3051 flag: &FloatSliceFlag{Name: "flag", Value: []float64{1.1, 2.2}},
3052 toParse: []string{"--flag", "13.3,14.4", "--flag", "15.5,16.6"},
3053 expect: `[]float64{13.3, 14.4, 15.5, 16.6}`,
3054 },
3055 {
3056 name: "intSlice",
3057 flag: &Int64SliceFlag{Name: "flag", Value: []int64{1, 2}},
3058 toParse: []string{"--flag", "13,14", "--flag", "15,16"},
3059 expect: `[]int64{13, 14, 15, 16}`,
3060 },
3061 {
3062 name: "uintSlice",
3063 flag: &Uint64SliceFlag{Name: "flag", Value: []uint64{1, 2}},
3064 toParse: []string{"--flag", "13,14", "--flag", "15,16"},
3065 expect: `[]uint64{13, 14, 15, 16}`,
3066 },
3067 {
3068 name: "stringMap",
3069 flag: &StringMapFlag{Name: "flag", Value: map[string]string{"default1": "default2"}},
3070 toParse: []string{"--flag", "parsed=parsed2", "--flag", "parsed3=parsed4"},
3071 expect: `map[parsed:parsed2 parsed3:parsed4]`,
3072 },
3073 {
3074 name: "int",
3075 flag: &IntFlag{Name: "flag", Value: 1},
3076 toParse: []string{"--flag", "42"},
3077 expect: `int(42)`,
3078 },
3079 {
3080 name: "uint",
3081 flag: &UintFlag{Name: "flag", Value: 1},
3082 toParse: []string{"--flag", "42"},
3083 expect: `uint(42)`,
3084 },
3085 }
3086 for _, v := range cases {
3087 t.Run(v.name, func(t *testing.T) {
3088 cmd := &Command{
3089 Flags: []Flag{
3090 v.flag,
3091 },
3092 }
3093 assert.NoError(t, cmd.Run(buildTestContext(t), append([]string{""}, v.toParse...)))
3094 f := cmd.lookupFlag("flag")
3095 require.Equal(t, v.expect, f.String())
3096 })
3097 }
3098 }
3099
3100 func TestTimestampFlagApply_WithDestination(t *testing.T) {
3101 var destination time.Time
3102 expectedResult, _ := time.Parse(time.RFC3339, "2006-01-02T15:04:05Z")
3103 fl := TimestampFlag{Name: "time", Aliases: []string{"t"}, Config: TimestampConfig{Layouts: []string{time.RFC3339}}, Destination: &destination}
3104 cmd := &Command{
3105 Flags: []Flag{
3106 &fl,
3107 },
3108 }
3109
3110 assert.NoError(t, cmd.Run(buildTestContext(t), []string{"", "--time", "2006-01-02T15:04:05Z"}))
3111 assert.Equal(t, expectedResult, destination)
3112 }
3113
3114 // Test issue #1254
3115 // StringSlice() with UseShortOptionHandling causes duplicated entries, depending on the ordering of the flags
3116 func TestSliceShortOptionHandle(t *testing.T) {
3117 wasCalled := false
3118 err := (&Command{
3119 Name: "foobar",
3120 UseShortOptionHandling: true,
3121 Action: func(_ context.Context, cmd *Command) error {
3122 wasCalled = true
3123
3124 if !cmd.Bool("i") {
3125 return fmt.Errorf("bool i not set")
3126 }
3127
3128 if !cmd.Bool("t") {
3129 return fmt.Errorf("bool i not set")
3130 }
3131
3132 ss := cmd.StringSlice("net")
3133 if !reflect.DeepEqual(ss, []string{"foo"}) {
3134 return fmt.Errorf("got different slice %q than expected", ss)
3135 }
3136
3137 return nil
3138 },
3139 Flags: []Flag{
3140 &StringSliceFlag{Name: "net"},
3141 &BoolFlag{Name: "i"},
3142 &BoolFlag{Name: "t"},
3143 },
3144 }).Run(buildTestContext(t), []string{"foobar", "--net=foo", "-it"})
3145
3146 r := require.New(t)
3147
3148 r.NoError(err)
3149 r.Truef(wasCalled, "action callback was never called")
3150 }
3151
3152 // Test issue #1541
3153 func TestCustomizedSliceFlagSeparator(t *testing.T) {
3154 opts := []string{"opt1", "opt2", "opt3,op", "opt4"}
3155 ret := flagSplitMultiValues(strings.Join(opts, ";"), ";", disableSliceFlagSeparator)
3156 require.Equal(t, 4, len(ret), "split slice flag failed")
3157 for idx, r := range ret {
3158 require.Equal(t, opts[idx], r, "get %dth failed", idx)
3159 }
3160 }
3161
3162 func TestFlagSplitMultiValues_Disabled(t *testing.T) {
3163 opts := []string{"opt1", "opt2", "opt3,op", "opt4"}
3164 ret := flagSplitMultiValues(strings.Join(opts, defaultSliceFlagSeparator), defaultSliceFlagSeparator, true)
3165 require.Equal(t, 1, len(ret), "failed to disable split slice flag")
3166 require.Equal(t, strings.Join(opts, defaultSliceFlagSeparator), ret[0])
3167 }
3168
3169 var stringMapFlagTests = []struct {
3170 name string
3171 aliases []string
3172 value map[string]string
3173 expected string
3174 }{
3175 {"foo", nil, nil, "--foo string=string [ --foo string=string ]\t"},
3176 {"f", nil, nil, "-f string=string [ -f string=string ]\t"},
3177 {"f", nil, map[string]string{"Lipstick": ""}, "-f string=string [ -f string=string ]\t(default: Lipstick=)"},
3178 {"test", nil, map[string]string{"Something": ""}, "--test string=string [ --test string=string ]\t(default: Something=)"},
3179 {"dee", []string{"d"}, map[string]string{"Inka": "Dinka", "dooo": ""}, "--dee string=string, -d string=string [ --dee string=string, -d string=string ]\t(default: Inka=\"Dinka\", dooo=)"},
3180 }
3181
3182 func TestStringMapFlagHelpOutput(t *testing.T) {
3183 for _, test := range stringMapFlagTests {
3184 f := &StringMapFlag{Name: test.name, Aliases: test.aliases, Value: test.value}
3185 assert.Equal(t, test.expected, f.String())
3186 }
3187 }
3188
3189 func TestStringMapFlagWithEnvVarHelpOutput(t *testing.T) {
3190 t.Setenv("APP_QWWX", "11,4")
3191
3192 for _, test := range stringMapFlagTests {
3193 fl := &StringMapFlag{Name: test.name, Aliases: test.aliases, Value: test.value, Sources: EnvVars("APP_QWWX")}
3194 output := fl.String()
3195
3196 expectedSuffix := withEnvHint([]string{"APP_QWWX"}, "")
3197 if !strings.HasSuffix(output, expectedSuffix) {
3198 t.Errorf("%q does not end with"+expectedSuffix, output)
3199 }
3200 }
3201 }
3202
3203 func TestStringMapFlagApply_SetsAllNames(t *testing.T) {
3204 fl := StringMapFlag{Name: "goat", Aliases: []string{"G", "gooots"}}
3205 cmd := &Command{
3206 Flags: []Flag{
3207 &fl,
3208 },
3209 }
3210
3211 assert.NoError(t, cmd.Run(buildTestContext(t), []string{"", "--goat", "aaa=", "-G", "bbb=", "--gooots", "eeeee="}))
3212 }
3213
3214 func TestStringMapFlagApply_UsesEnvValues_noDefault(t *testing.T) {
3215 t.Setenv("MY_GOAT", "vincent van goat=scape goat")
3216 var val map[string]string
3217 fl := StringMapFlag{Name: "goat", Sources: EnvVars("MY_GOAT"), Value: val}
3218 cmd := &Command{
3219 Flags: []Flag{
3220 &fl,
3221 },
3222 }
3223
3224 assert.NoError(t, cmd.Run(buildTestContext(t), []string{""}))
3225 assert.Nil(t, val)
3226 assert.Equal(t, map[string]string{"vincent van goat": "scape goat"}, cmd.Value("goat"))
3227 }
3228
3229 func TestStringMapFlagApply_UsesEnvValues_withDefault(t *testing.T) {
3230 t.Setenv("MY_GOAT", "vincent van goat=scape goat")
3231 val := map[string]string{`some default`: `values here`}
3232 fl := StringMapFlag{Name: "goat", Sources: EnvVars("MY_GOAT"), Value: val}
3233 cmd := &Command{
3234 Flags: []Flag{
3235 &fl,
3236 },
3237 }
3238
3239 assert.NoError(t, cmd.Run(buildTestContext(t), []string{""}))
3240 assert.Equal(t, map[string]string{`some default`: `values here`}, val)
3241 assert.Equal(t, map[string]string{"vincent van goat": "scape goat"}, cmd.Value("goat"))
3242 }
3243
3244 func TestStringMapFlagApply_DefaultValueWithDestination(t *testing.T) {
3245 defValue := map[string]string{"UA": "US"}
3246
3247 fl := StringMapFlag{Name: "country", Value: defValue, Destination: &map[string]string{"CA": ""}}
3248 cmd := &Command{
3249 Flags: []Flag{
3250 &fl,
3251 },
3252 }
3253
3254 assert.NoError(t, cmd.Run(buildTestContext(t), []string{""}))
3255 assert.Equal(t, defValue, *fl.Destination)
3256 }
3257
3258 func TestStringMapFlagValueFromCommand(t *testing.T) {
3259 f := &StringMapFlag{Name: "myflag"}
3260 cmd := &Command{
3261 Flags: []Flag{
3262 f,
3263 },
3264 }
3265 assert.NoError(t, cmd.Run(buildTestContext(t), []string{""}))
3266 require.NoError(t, cmd.Set("myflag", "a=b"))
3267 require.NoError(t, cmd.Set("myflag", "c="))
3268
3269 require.Equal(t, map[string]string{"a": "b", "c": ""}, cmd.StringMap(f.Name))
3270 }
3271
3272 func TestStringMapFlagApply_Error(t *testing.T) {
3273 fl := StringMapFlag{Name: "goat"}
3274 cmd := &Command{
3275 Flags: []Flag{
3276 &fl,
3277 },
3278 }
3279
3280 assert.Error(t, cmd.Run(buildTestContext(t), []string{"", "--goat", "aaa", "bbb="}))
3281 }
3282
3283 func TestZeroValueMutexFlag(t *testing.T) {
3284 var fl MutuallyExclusiveFlags
3285 assert.NoError(t, fl.check(&Command{}))
3286 }
3287
3288 func TestMutexFlagCategory(t *testing.T) {
3289 cmd := buildMinimalTestCommand()
3290 cmd.Category = "TestCmd"
3291 cmd.MutuallyExclusiveFlags = []MutuallyExclusiveFlags{
3292 {
3293 Flags: [][]Flag{
3294 {
3295 &StringFlag{Name: "foo", Category: "Group1"},
3296 &IntFlag{Name: "bar", Category: "Group1"},
3297 },
3298 {
3299 &StringFlag{Name: "baz", Category: "Group2"},
3300 },
3301 },
3302 },
3303 }
3304
3305 assert.NoError(t, cmd.Run(buildTestContext(t), []string{"", "--foo", "value"}))
3306 }
3307
3308 func TestExtFlag(t *testing.T) {
3309 var iv intValue[int64]
3310 var ipv int64
3311
3312 f := &flag.Flag{
3313 Name: "bar",
3314 Usage: "bar usage",
3315 Value: iv.Create(11, &ipv, IntegerConfig{}),
3316 DefValue: "10",
3317 }
3318
3319 extF := &extFlag{
3320 f: f,
3321 }
3322
3323 assert.Equal(t, []string{"bar"}, extF.Names())
3324 assert.True(t, extF.IsVisible())
3325 assert.False(t, extF.IsSet())
3326 assert.False(t, extF.TakesValue())
3327 assert.Equal(t, "bar usage", extF.GetUsage())
3328 assert.Equal(t, "11", extF.GetValue())
3329 assert.Equal(t, "10", extF.GetDefaultText())
3330 assert.Nil(t, extF.GetEnvVars())
3331
3332 assert.Equal(t, "integer", extF.SchemaType())
3333 assert.Equal(t, "", extF.SchemaItemsType())
3334 }
3335
3336 func TestSliceValuesNil(t *testing.T) {
3337 assert.Equal(t, []float64(nil), NewFloatSlice().Value())
3338 assert.Equal(t, []float32(nil), NewFloat32Slice().Value())
3339 assert.Equal(t, []float64(nil), NewFloat64Slice().Value())
3340 assert.Equal(t, []int64(nil), NewInt64Slice().Value())
3341 assert.Equal(t, []uint64(nil), NewUint64Slice().Value())
3342 assert.Equal(t, []string(nil), NewStringSlice().Value())
3343
3344 assert.Equal(t, []float64(nil), (&FloatSlice{}).Value())
3345 assert.Equal(t, []float32(nil), (&Float32Slice{}).Value())
3346 assert.Equal(t, []float64(nil), (&Float64Slice{}).Value())
3347 assert.Equal(t, []int64(nil), (&Int64Slice{}).Value())
3348 assert.Equal(t, []uint64(nil), (&Uint64Slice{}).Value())
3349 assert.Equal(t, []string(nil), (&StringSlice{}).Value())
3350 }
3351
3352 func TestFileHint(t *testing.T) {
3353 assert.Equal(t, "", withFileHint("", ""))
3354 assert.Equal(t, " [/tmp/foo.txt]", withFileHint("/tmp/foo.txt", ""))
3355 assert.Equal(t, "foo", withFileHint("", "foo"))
3356 assert.Equal(t, "bar [/tmp/foo.txt]", withFileHint("/tmp/foo.txt", "bar"))
3357 }
3358
3359 func TestHasFlags(t *testing.T) {
3360 flagToCheck := &StringFlag{Name: "foo"}
3361 flags := []Flag{
3362 &StringFlag{Name: "bar"},
3363 &Int64Flag{Name: "baz"},
3364 flagToCheck,
3365 }
3366
3367 assert.True(t, hasFlag(flags, flagToCheck))
3368 }
3369
3370 func TestFlagsByName(t *testing.T) {
3371 flags := []Flag{
3372 &StringFlag{
3373 Name: "b2",
3374 },
3375 &Int64Flag{
3376 Name: "a0",
3377 },
3378 &FloatFlag{
3379 Name: "b1",
3380 },
3381 }
3382
3383 flagsByName := FlagsByName(flags)
3384 sort.Sort(flagsByName)
3385
3386 assert.Equal(t, len(flags), flagsByName.Len())
3387
3388 var prev Flag
3389 for _, f := range flags {
3390 if prev != nil {
3391 assert.LessOrEqual(t, prev.Names()[0], f.Names()[0])
3392 }
3393 prev = f
3394 }
3395 }
3396
3397 func TestNonStringMap(t *testing.T) {
3398 type (
3399 floatMap = MapBase[float64, NoConfig, floatValue[float64]]
3400 )
3401
3402 p := map[string]float64{}
3403
3404 var fv floatValue[float64]
3405
3406 f := &floatMap{
3407 value: &fv,
3408 }
3409
3410 assert.Equal(t, map[string]float64{}, f.Value())
3411 f.dict = &p
3412 assert.Equal(t, map[string]float64{}, f.Value())
3413 assert.Equal(t, "map[string]float64{}", f.String())
3414
3415 assert.ErrorContains(t, f.Set("invalid=value"), "ParseFloat")
3416 }
3417
3418 func TestUnquoteUsage(t *testing.T) {
3419 tests := []struct {
3420 str string
3421 expStr string
3422 expUsage string
3423 }{
3424 {"foo", "", "foo"},
3425 {"foo something", "", "foo something"},
3426 {"foo `bar 11`", "bar 11", "foo bar 11"},
3427 {"foo `bar 11` sobar", "bar 11", "foo bar 11 sobar"},
3428 {"foo `bar 11", "", "foo `bar 11"},
3429 }
3430
3431 for i, test := range tests {
3432 t.Run(fmt.Sprintf("unquote %d", i), func(t *testing.T) {
3433 str, usage := unquoteUsage(test.str)
3434 assert.Equal(t, test.expStr, str)
3435 assert.Equal(t, test.expUsage, usage)
3436 })
3437 }
3438 }
3439
3440 func TestEnvHintWindows(t *testing.T) {
3441 if runtime.GOOS == "windows" && os.Getenv("PSHOME") == "" {
3442 assert.Equal(t, "something [%foo%, %bar%, %ss%]", withEnvHint([]string{"foo", "bar", "ss"}, "something"))
3443 }
3444 }
3445
3446 func TestDocGetValue(t *testing.T) {
3447 assert.Equal(t, "true", (&BoolFlag{Name: "foo", Value: true}).GetValue())
3448 assert.Equal(t, "false", (&BoolFlag{Name: "foo", Value: false}).GetValue())
3449 assert.Equal(t, "\"bar\"", (&StringFlag{Name: "foo", Value: "bar"}).GetValue())
3450 assert.Equal(t, "", (&BoolWithInverseFlag{Name: "foo", Value: false}).GetValue())
3451 }
3452
3453 func TestGenericFlag_SatisfiesFlagInterface(t *testing.T) {
3454 var f Flag = &GenericFlag{}
3455
3456 _ = f.IsSet()
3457 _ = f.Names()
3458 }
3459
3460 func TestGenericValue_SatisfiesBoolInterface(t *testing.T) {
3461 var f boolFlag = &genericValue{}
3462 var fpv float64
3463
3464 assert.False(t, f.IsBoolFlag())
3465
3466 fv := floatValue[float64]{val: &fpv}
3467 f = &genericValue{
3468 val: &fv,
3469 }
3470
3471 assert.False(t, f.IsBoolFlag())
3472
3473 f = &genericValue{
3474 val: &boolValue{},
3475 }
3476 assert.True(t, f.IsBoolFlag())
3477 }
3478
3479 func TestGenericFlag_SatisfiesFmtStringerInterface(t *testing.T) {
3480 var f fmt.Stringer = &GenericFlag{}
3481
3482 _ = f.String()
3483 }
3484
3485 func TestGenericFlag_SatisfiesRequiredFlagInterface(t *testing.T) {
3486 var f RequiredFlag = &GenericFlag{}
3487
3488 _ = f.IsRequired()
3489 }
3490
3491 func TestGenericFlag_SatisfiesVisibleFlagInterface(t *testing.T) {
3492 var f VisibleFlag = &GenericFlag{}
3493
3494 _ = f.IsVisible()
3495 }
3496
3497 func TestGenericFlag_SatisfiesDocFlagInterface(t *testing.T) {
3498 var f DocGenerationFlag = &GenericFlag{}
3499
3500 _ = f.GetUsage()
3501 }
3502
3503 func TestGenericValue(t *testing.T) {
3504 g := &genericValue{}
3505 assert.NoError(t, g.Set("something"))
3506 assert.Nil(t, g.Get())
3507 assert.Empty(t, g.String())
3508 }
3509
3510 func TestEndValue(t *testing.T) {
3511 cmd := buildMinimalTestCommand()
3512 cmd.UseShortOptionHandling = true
3513 cmd.Flags = []Flag{
3514 &IntFlag{Name: "debug", Aliases: []string{"d"}},
3515 &IntFlag{Name: "count", Aliases: []string{"c"}},
3516 }
3517
3518 assert.Error(t, cmd.Run(buildTestContext(t), []string{"foo", "-cd="}))
3519 assert.Error(t, cmd.Run(buildTestContext(t), []string{"foo", "-cd=s"}))
3520 }