1 package ffyaml_test
2
3 import (
4 "flag"
5 "os"
6 "testing"
7 "time"
8
9 "github.com/peterbourgon/ff/v3"
10 "github.com/peterbourgon/ff/v3/fftest"
11 "github.com/peterbourgon/ff/v3/ffyaml"
12 )
13
14 func TestParser(t *testing.T) {
15 t.Parallel()
16
17 for _, testcase := range []struct {
18 vars func(*flag.FlagSet) *fftest.Vars
19 name string
20 file string
21 miss bool
22 want fftest.Vars
23 }{
24 {
25 name: "empty",
26 file: "testdata/empty.yaml",
27 want: fftest.Vars{},
28 },
29 {
30 name: "basic KV pairs",
31 file: "testdata/basic.yaml",
32 want: fftest.Vars{S: "hello", I: 10, B: true, D: 5 * time.Second, F: 3.14},
33 },
34 {
35 name: "invalid prefix",
36 file: "testdata/invalid_prefix.yaml",
37 want: fftest.Vars{WantParseErrorString: "found character that cannot start any token"},
38 },
39 {
40 vars: fftest.NonzeroDefaultVars,
41 name: "no value for s",
42 file: "testdata/no_value_s.yaml",
43 want: fftest.Vars{S: "", I: 123, F: 9.99, B: true, D: 3 * time.Hour},
44 },
45 {
46 vars: fftest.NonzeroDefaultVars,
47 name: "no value for i",
48 file: "testdata/no_value_i.yaml",
49 want: fftest.Vars{WantParseErrorString: "parse error"},
50 },
51 {
52 name: "basic arrays",
53 file: "testdata/basic_array.yaml",
54 want: fftest.Vars{S: "c", X: []string{"a", "b", "c"}},
55 },
56 {
57 name: "multiline arrays",
58 file: "testdata/multi_line_array.yaml",
59 want: fftest.Vars{S: "c", X: []string{"d", "e", "f"}},
60 },
61 {
62 name: "line break arrays",
63 file: "testdata/line_break_array.yaml",
64 want: fftest.Vars{X: []string{"first string", "second string", "third"}},
65 },
66 {
67 name: "unquoted strings in arrays",
68 file: "testdata/unquoted_string_array.yaml",
69 want: fftest.Vars{X: []string{"one", "two", "three"}},
70 },
71 {
72 name: "missing config file allowed",
73 file: "testdata/this_file_does_not_exist.yaml",
74 miss: true,
75 want: fftest.Vars{},
76 },
77 {
78 name: "missing config file not allowed",
79 file: "testdata/this_file_does_not_exist.yaml",
80 miss: false,
81 want: fftest.Vars{WantParseErrorIs: os.ErrNotExist},
82 },
83 } {
84 t.Run(testcase.name, func(t *testing.T) {
85 if testcase.vars == nil {
86 testcase.vars = fftest.DefaultVars
87 }
88 fs := flag.NewFlagSet("fftest", flag.ContinueOnError)
89 vars := testcase.vars(fs)
90 vars.ParseError = ff.Parse(fs, []string{},
91 ff.WithConfigFile(testcase.file),
92 ff.WithConfigFileParser(ffyaml.Parser),
93 ff.WithAllowMissingConfigFile(testcase.miss),
94 )
95 fftest.Compare(t, &testcase.want, vars)
96 })
97 }
98 }
99
View as plain text