~mna/snow unlisted

ref: b80c93389bef70627bad6a5d2db7398350b0ef65 snow/cmd/internal/flag/flag_test.go -rw-r--r-- 5.4 KiB
b80c9338Martin Angers cmd/internal: add packages for command-line 1 year, 4 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
package flag

import (
	"errors"
	"fmt"
	"os"
	"strings"
	"testing"
	"time"

	"github.com/stretchr/testify/require"
)

type F struct {
	S     string        `flag:"s,string,long-string"`
	I     int           `flag:"i,int"`
	B     bool          `flag:"b"`
	H     bool          `flag:"h,help"`
	T     time.Duration `flag:"t"`
	N     int
	args  []string
	flags map[string]bool
}

func (f *F) SetArgs(args []string) {
	f.args = args
}

func (f *F) SetFlags(flags map[string]bool) {
	f.flags = flags
}

func TestParseFlags(t *testing.T) {
	cases := []struct {
		args []string
		want *F
		err  string
	}{
		{
			want: &F{},
		},
		{
			args: []string{"toto"},
			want: &F{
				args: []string{"toto"},
			},
		},
		{
			args: []string{"-h"},
			want: &F{
				H:     true,
				flags: map[string]bool{"h": true},
			},
		},
		{
			args: []string{"-i", "10", "--int", "20"},
			want: &F{
				I:     20,
				flags: map[string]bool{"i": true, "int": true},
			},
		},
		{
			args: []string{"-i", "10", "--int", "20"},
			want: &F{
				I:     20,
				flags: map[string]bool{"i": true, "int": true},
			},
		},
		{
			args: []string{"-s", "a", "--string", "b", "-long-string", "c"},
			want: &F{
				S:     "c",
				flags: map[string]bool{"s": true, "string": true, "long-string": true},
			},
		},
		{
			args: []string{"-b", "--b", "-b"},
			want: &F{
				B:     true,
				flags: map[string]bool{"b": true},
			},
		},
		{
			args: []string{"-b", "-int", "1", "-string", "a", "arg1", "arg2"},
			want: &F{
				B:     true,
				I:     1,
				S:     "a",
				args:  []string{"arg1", "arg2"},
				flags: map[string]bool{"b": true, "int": true, "string": true},
			},
		},
		{
			args: []string{"-n", "1"},
			want: &F{},
			err:  "not defined: -n",
		},
		{
			args: []string{"-t", "3s"},
			want: &F{
				T:     3 * time.Second,
				flags: map[string]bool{"t": true},
			},
		},
		{
			args: []string{"-t", "nope"},
			want: &F{},
			err:  "invalid value",
		},
	}

	var p Parser
	for _, c := range cases {
		t.Run(strings.Join(c.args, " "), func(t *testing.T) {
			var f F
			args := append([]string{""}, c.args...)
			err := p.Parse(args, &f)

			if c.err != "" {
				require.Error(t, err)
				require.Contains(t, err.Error(), c.err)
				return
			}

			require.NoError(t, err)
			require.Equal(t, c.want, &f)
		})
	}
}

func TestParseNoFlag(t *testing.T) {
	type F struct {
		V int
	}
	var p Parser

	f := F{V: 4}
	err := p.Parse([]string{"", "x"}, &f)
	require.NoError(t, err)
	require.Equal(t, 4, f.V)
}

type noFlagSetArgs struct {
	args []string
}

func (n *noFlagSetArgs) SetArgs(args []string) {
	n.args = args
}

func TestParseNoFlagSetArgs(t *testing.T) {
	var p Parser
	f := noFlagSetArgs{}
	err := p.Parse([]string{"", "x"}, &f)
	require.NoError(t, err)
	require.Equal(t, []string{"x"}, f.args)
}

func TestParseArgsError(t *testing.T) {
	type F struct {
		X bool `flag:"x"`
	}
	var p Parser
	f := F{}
	err := p.Parse([]string{"", "-zz"}, &f)
	require.Error(t, err)
	require.Contains(t, err.Error(), "-zz")
}

func TestParseNotStructPointer(t *testing.T) {
	var (
		i int
		p Parser
	)
	require.Panics(t, func() {
		_ = p.Parse([]string{"-h"}, i)
	})
}

func TestParseUnsupportedFlagType(t *testing.T) {
	type F struct {
		C *bool `flag:"c"`
	}
	var (
		f F
		p Parser
	)
	require.Panics(t, func() {
		_ = p.Parse([]string{"", "-h"}, &f)
	})
}

type E struct {
	Addr    string `flag:"addr"`
	DB      string `flag:"db"`
	Help    bool   `flag:"h,help" ignored:"true"`
	Version bool   `flag:"v,version" ignored:"true"`
}

func (e *E) Validate() error {
	if e.Help || e.Version {
		return nil
	}
	if e.Addr == "" {
		return errors.New("address must be set")
	}
	if e.DB == "" {
		return errors.New("db must be set")
	}
	return nil
}

func TestParseEnvVars(t *testing.T) {
	const progName = "mainer-test"

	p := Parser{
		EnvVars: true,
	}

	cases := []struct {
		env    string // prefix-less Key:val pairs, space-separated
		args   string // space-separated, index 0 added automatically
		want   E
		errMsg string // error must contain that errMsg
	}{
		{
			"",
			"",
			E{},
			"address must be set",
		},
		{
			"ADDR::1234 DB:x",
			"",
			E{Addr: ":1234", DB: "x"},
			"",
		},
		{
			"",
			"-addr :2345 -db v",
			E{Addr: ":2345", DB: "v"},
			"",
		},
		{
			"ADDR::1234",
			"-addr :2345 -db x",
			E{Addr: ":2345", DB: "x"},
			"",
		},
		{
			"HELP:true",
			"-addr :2345",
			E{Addr: ":2345"},
			"db must be set",
		},
		{
			"VERSION:1",
			"-addr :2345 -db x",
			E{Addr: ":2345", DB: "x"},
			"",
		},
		{
			"",
			"-help",
			E{Help: true},
			"",
		},
		{
			"",
			"-v",
			E{Version: true},
			"",
		},
		{
			"",
			"-z",
			E{},
			"flag provided but not defined: -z",
		},
	}
	for _, c := range cases {
		t.Run(fmt.Sprintf("%s|%s", c.env, c.args), func(t *testing.T) {
			// set env vars
			if c.env != "" {
				envPairs := strings.Split(c.env, " ")
				for _, pair := range envPairs {
					ix := strings.Index(pair, ":")
					require.True(t, ix >= 0, "%s: missing colon", pair)
					key, val := pair[:ix], pair[ix+1:]
					key = strings.ToUpper(prefixFromProgramName(progName)) + "_" + key
					os.Setenv(key, val)
					defer os.Unsetenv(key)
				}
			}

			// parse args
			args := []string{progName}
			if c.args != "" {
				args = append(args, strings.Split(c.args, " ")...)
			}

			var e E
			err := p.Parse(args, &e)
			if c.errMsg != "" {
				require.Error(t, err)
				require.Contains(t, err.Error(), c.errMsg)
			} else {
				require.NoError(t, err)
			}

			require.Equal(t, c.want, e)
		})
	}
}