-
Notifications
You must be signed in to change notification settings - Fork 3
/
provider_test.go
421 lines (348 loc) · 12 KB
/
provider_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
package config
import (
"fmt"
"reflect"
"strings"
"testing"
"time"
"github.com/ThomasObenaus/go-conf/interfaces"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func toProviderImpl(t *testing.T, pIf interfaces.Provider) *providerImpl {
p, ok := pIf.(*providerImpl)
require.True(t, ok)
require.NotNil(t, p)
return p
}
func Test_wrap(t *testing.T) {
// GIVEN
txt1 := "Hello World"
txt2 := "Hello"
txt3 := "Hello World , hello world "
// WHEN
wrapped1 := wrapText(txt1, 5, "\n")
wrapped2 := wrapText(txt2, 5, "\n")
wrapped3 := wrapText(txt3, 5, "\n")
// THEN
assert.Equal(t, "Hello\nWorld", wrapped1)
assert.Equal(t, "Hello", wrapped2)
assert.Equal(t, "Hello\nWorld\n, hel\nlo wo\nrld", wrapped3)
}
func Test_NewProvider(t *testing.T) {
// GIVEN
var configEntries []Entry
var args []string
configName := "testcfg"
envPrefix := "TST"
// WHEN
provider, err := NewProvider(configEntries, configName, envPrefix)
require.NoError(t, err)
err = provider.ReadConfig(args)
// THEN
pImpl := toProviderImpl(t, provider)
assert.NotNil(t, pImpl.pFlagSet)
assert.NotNil(t, pImpl.Viper)
assert.Equal(t, envPrefix, pImpl.envPrefix)
assert.NoError(t, err)
assert.Len(t, pImpl.AllKeys(), 1)
assert.Equal(t, "config-file", pImpl.configFileEntry.name)
assert.Empty(t, pImpl.configFileEntry.flagShortName)
}
func Test_NewProviderOverrideCfgFile(t *testing.T) {
// GIVEN
var configEntries []Entry
configName := "testcfg"
envPrefix := "TST"
// WHEN
provider, err := NewProvider(configEntries, configName, envPrefix, CfgFile("cfg-f", "f"))
require.NoError(t, err)
// THEN
pImpl := toProviderImpl(t, provider)
assert.NotNil(t, pImpl.pFlagSet)
assert.NotNil(t, pImpl.Viper)
assert.Equal(t, envPrefix, pImpl.envPrefix)
assert.Equal(t, "cfg-f", pImpl.configFileEntry.name)
assert.Equal(t, "f", pImpl.configFileEntry.flagShortName)
}
func Test_RegisterMappingFunc(t *testing.T) {
// GIVEN
type myCfg struct {
}
cfg := myCfg{}
provider, err := NewConfigProvider(&cfg, "MyConfig", "MY_APP")
require.NoError(t, err)
// WHEN
err1 := provider.RegisterMappingFunc("fun", func(rawUntypedValue interface{}, targetType reflect.Type) (interface{}, error) {
return rawUntypedValue, nil
})
err2 := provider.RegisterMappingFunc("fun", nil)
err3 := provider.RegisterMappingFunc("", func(rawUntypedValue interface{}, targetType reflect.Type) (interface{}, error) {
return rawUntypedValue, nil
})
// THEN
assert.NoError(t, err1)
assert.Error(t, err2)
assert.Error(t, err3)
}
func Test_Duration(t *testing.T) {
// GIVEN
type myCfg struct {
Field1 time.Duration `cfg:"{'name':'field-1','desc':'This is field 1'}"`
}
cfg := myCfg{}
provider, err := NewConfigProvider(&cfg, "MyConfig", "MY_APP")
require.NoError(t, err)
args := []string{
"--field-1=12h",
}
// WHEN
err = provider.ReadConfig(args)
require.NoError(t, err)
// THEN
dur := provider.GetDuration("field-1")
assert.Equal(t, time.Hour*12, dur)
}
func Test_Things(t *testing.T) {
// GIVEN
entry := NewEntry("things", "A list of things [{'user':'user1','age':25},{'user':'user2','age':55}]. The user has to be unique.", Default(""))
type myCfg struct {
}
cfg := myCfg{}
provider, err := NewConfigProvider(&cfg, "MyConfig", "MY_APP", CustomConfigEntries([]Entry{entry}))
require.NoError(t, err)
args := []string{
"--config-file=test/data/things.yaml",
}
// WHEN
err = provider.ReadConfig(args)
require.NoError(t, err)
// THEN
things := provider.Get("things")
assert.NotEmpty(t, things)
assert.Equal(t, []interface{}{
map[interface{}]interface{}{"age": 25, "user": "user1"},
map[interface{}]interface{}{"age": 55, "user": "user2"},
}, things)
}
func ExampleNewProvider() {
var configEntries []Entry
configEntries = append(configEntries, NewEntry("port", "the port to listen to", Default(8080), ShortName("p")))
// no default value for this parameter --> thus it can be treated as a required one
// to check if it was set by the user one can just call provider.IsSet("db-url")
configEntries = append(configEntries, NewEntry("db-url", "the address of the data base"))
configEntries = append(configEntries, NewEntry("db-reconnect", "enable automatic reconnect to the data base", Default(false)))
provider, err := NewProvider(configEntries, "my-config", "MY_APP")
if err != nil {
panic(err)
}
args := []string{"--db-url=http://localhost"}
err = provider.ReadConfig(args)
if err != nil {
panic(err)
}
port := provider.GetInt("port")
// check for mandatory parameter
if !provider.IsSet("db-url") {
panic(fmt.Errorf("Parameter '--db-url' is missing"))
}
dbURL := provider.GetString("db-url")
dbReconnect := provider.GetBool("db-reconnect")
fmt.Printf("port=%d, dbURL=%s, dbReconnect=%t", port, dbURL, dbReconnect)
// Output:
// port=8080, dbURL=http://localhost, dbReconnect=false
}
func ExampleNewProvider_withConfigFile() {
var configEntries []Entry
configEntries = append(configEntries, NewEntry("port", "the port to listen to", Default(8080), ShortName("p")))
provider, err := NewProvider(configEntries, "my-config", "MY_APP")
if err != nil {
panic(err)
}
args := []string{"--config-file=test/data/config.yaml"}
err = provider.ReadConfig(args)
if err != nil {
panic(err)
}
port := provider.GetInt("port")
cfgFile := provider.GetString("config-file")
fmt.Printf("port=%d was read from cfgFile=%s", port, cfgFile)
// Output:
// port=12345 was read from cfgFile=test/data/config.yaml
}
func ExampleNewConfigProvider_primitiveTypes() {
// The configuration with the annotations needed in order to define how the config should be filled
type myCfg struct {
Field1 string `cfg:"{'name':'field-1','desc':'This is field 1','default':'default value for field 1'}"`
Field2 int `cfg:"{'name':'field-2','desc':'This is field 2','default':11}"`
Field3 bool `cfg:"{'name':'field-3','desc':'This is field 3','default':false}"`
Field4 time.Duration `cfg:"{'name':'field-4','desc':'This is field 4','default':'5m'}"`
}
cfg := myCfg{}
// Create a provider based on the given config struct
provider, err := NewConfigProvider(&cfg, "MyConfig", "MY_APP")
if err != nil {
panic(err)
}
// As commandline arguments the parameter 'field-1' is missing, hence its default value will be used (see above)
args := []string{"--field-2=22", "--field-3", "--field-4=10m"}
// Read the parameters given via commandline into the config struct
err = provider.ReadConfig(args)
if err != nil {
panic(err)
}
fmt.Printf("field-1='%s', field-2=%d, field-3=%t, field-4=%s\n", cfg.Field1, cfg.Field2, cfg.Field3, cfg.Field4)
// Output:
// field-1='default value for field 1', field-2=22, field-3=true, field-4=10m0s
}
func ExampleNewConfigProvider_slices() {
// The configuration with the annotations needed in order to define how the config should be filled
type myCfg struct {
Field1 []string `cfg:"{'name':'field-1','desc':'This is field 1','default':['a','b','c']}"`
Field2 []int `cfg:"{'name':'field-2','desc':'This is field 2','default':[1,2,3]}"`
Field3 []bool `cfg:"{'name':'field-3','desc':'This is field 3','default':[true,false,true]}"`
Field4 []float64 `cfg:"{'name':'field-4','desc':'This is field 4','default':[1.1,2.2,3.3]}"`
}
cfg := myCfg{}
// Create a provider based on the given config struct
provider, err := NewConfigProvider(&cfg, "MyConfig", "MY_APP")
if err != nil {
panic(err)
}
// As commandline arguments the parameter 'field-1' is missing, hence its default value will be used (see above)
args := []string{
"--field-2=4,5,6",
"--field-3=false,true",
"--field-4=4.4,5.5,6.6",
}
// Read the parameters given via commandline into the config struct
err = provider.ReadConfig(args)
if err != nil {
panic(err)
}
fmt.Printf("field-1='%v', field-2=%v, field-3=%v\n", cfg.Field1, cfg.Field2, cfg.Field3)
// Output:
// field-1='[a b c]', field-2=[4 5 6], field-3=[false true]
}
func ExampleNewConfigProvider_structs() {
type myNestedStruct struct {
FieldA string `cfg:"{'name':'field-a','desc':'This is field a','default':'default of field a'}"`
FieldB int `cfg:"{'name':'field-b','desc':'This is field b','default':22}"`
}
// The configuration with the annotations needed in order to define how the config should be filled
type myCfg struct {
Field1 myNestedStruct `cfg:"{'name':'field-1','desc':'This is field 1','default':{'field-a':'default','field-b':33}}"`
Field2 []myNestedStruct `cfg:"{'name':'field-2','desc':'This is field 2','default':[{'field-a':'value','field-b':33},{}]}"`
}
cfg := myCfg{}
// Create a provider based on the given config struct
provider, err := NewConfigProvider(&cfg, "MyConfig", "MY_APP")
if err != nil {
panic(err)
}
// As commandline arguments the parameter 'field-1' is missing, hence its default value will be used (see above)
args := []string{
"--field-1.field-a=the value",
}
// Read the parameters given via commandline into the config struct
err = provider.ReadConfig(args)
if err != nil {
panic(err)
}
fmt.Printf("field-1='%v', field-2=%v\n", cfg.Field1, cfg.Field2)
// Output:
// field-1='{the value 22}', field-2=[{value 33} {default of field a 22}]
}
func ExampleNewConfigProvider_mappingFunc() {
type logLevel int8
const (
llTrace logLevel = 0
llDebug logLevel = 1
llInfo logLevel = 2
llWarn logLevel = 3
llError logLevel = 4
)
// The configuration with the annotations needed in order to define how the config should be filled
type myCfg struct {
Field1 string `cfg:"{'name':'field-1','mapfun':'strToUpper','default':'HeLlO wOrLd'}"`
Field2 logLevel `cfg:"{'name':'field-2','mapfun':'strToLogLevel'}"`
}
cfg := myCfg{}
// Create a provider based on the given config struct
provider, err := NewConfigProvider(&cfg, "MyConfig", "MY_APP")
if err != nil {
panic(err)
}
// Register function to convert each string to upper case
err = provider.RegisterMappingFunc("strToUpper", func(rawUntypedValue interface{}, targetType reflect.Type) (interface{}, error) {
asStr, ok := rawUntypedValue.(string)
if !ok {
return nil, fmt.Errorf("Value must be a string")
}
return strings.ToUpper(asStr), nil
})
if err != nil {
panic(err)
}
// Register function to convert the given loglevel as string to the actual loglevel
err = provider.RegisterMappingFunc("strToLogLevel", func(rawUntypedValue interface{}, targetType reflect.Type) (interface{}, error) {
asStr, ok := rawUntypedValue.(string)
if !ok {
return nil, fmt.Errorf("Value must be a string")
}
switch asStr {
case "trace":
return llTrace, nil
case "debug":
return llDebug, nil
case "info":
return llInfo, nil
case "warn":
return llWarn, nil
case "error":
return llError, nil
default:
return nil, fmt.Errorf("loglevel %s unknown/ not supported", asStr)
}
})
if err != nil {
panic(err)
}
// As commandline arguments the parameter 'field-1' is missing, hence its default value will be used (see above)
args := []string{
"--field-2=warn",
}
// Read the parameters given via commandline into the config struct
err = provider.ReadConfig(args)
if err != nil {
panic(err)
}
fmt.Printf("field-1='%v', field-2='%v'\n", cfg.Field1, cfg.Field2)
// Output:
// field-1='HELLO WORLD', field-2='3'
}
func ExampleNewConfigProvider_usage() {
// The configuration with the annotations needed in order to define how the config should be filled
type myCfg struct {
//Field1 string `cfg:"{'name':'field-1','desc':'This is field 1','default':'default value for field 1'}"`
Field2 int `cfg:"{'name':'field-2','desc':'This is field 2. It is a required field since no default values is defined.'}"`
}
cfg := myCfg{}
// Create a provider based on the given config struct
provider, err := NewConfigProvider(&cfg, "MyConfig", "MY_APP")
if err != nil {
panic(err)
}
args := []string{"--field-2=22"}
// Read the parameters given via commandline into the config struct
err = provider.ReadConfig(args)
if err != nil {
panic(err)
}
fmt.Print(provider.Usage())
// Output:
//--field-2 (-) [required]
// env var: MY_APP_FIELD_2
// default: n/a
// desc: This is field 2. It is a required field since no default values is defined.
}