Debian Codegraph @

config/config_test.go

raw
1 /*
2 Copyright 2013-2014 Canonical Ltd.
3
4 This program is free software: you can redistribute it and/or modify it
5 under the terms of the GNU General Public License version 3, as published
6 by the Free Software Foundation.
7
8 This program is distributed in the hope that it will be useful, but
9 WITHOUT ANY WARRANTY; without even the implied warranties of
10 MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
11 PURPOSE. See the GNU General Public License for more details.
12
13 You should have received a copy of the GNU General Public License along
14 with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16
17 package config
18
19 import (
20 "bytes"
21 "encoding/json"
22 "flag"
23 "fmt"
24 "io/ioutil"
25 "os"
26 "path/filepath"
27 "reflect"
28 "testing"
29 "time"
30
31 . "gopkg.in/check.v1"
32 )
33
34 func TestConfig(t *testing.T) { TestingT(t) }
35
36 type configSuite struct{}
37
38 var _ = Suite(&configSuite{})
39
40 type testConfig1 struct {
41 A int
42 B string
43 C []string `json:"c_list"`
44 }
45
46 func (s *configSuite) TestReadConfig(c *C) {
47 buf := bytes.NewBufferString(`{"a": 1, "b": "foo", "c_list": ["c", "d", "e"]}`)
48 var cfg testConfig1
49 err := ReadConfig(buf, &cfg)
50 c.Check(err, IsNil)
51 c.Check(cfg, DeepEquals, testConfig1{A: 1, B: "foo", C: []string{"c", "d", "e"}})
52 }
53
54 func checkError(c *C, config string, dest interface{}, expectedError string) {
55 buf := bytes.NewBufferString(config)
56 err := ReadConfig(buf, dest)
57 c.Check(err, ErrorMatches, expectedError)
58 }
59
60 func (s *configSuite) TestReadConfigErrors(c *C) {
61 var cfg testConfig1
62 checkError(c, "", cfg, `destConfig not \*struct`)
63 var i int
64 checkError(c, "", &i, `destConfig not \*struct`)
65 checkError(c, "", &cfg, `EOF`)
66 checkError(c, `{"a": "1"}`, &cfg, `a: .*type int`)
67 checkError(c, `{"b": "1"}`, &cfg, `missing a`)
68 checkError(c, `{"A": "1"}`, &cfg, `missing a`)
69 checkError(c, `{"a": 1, "b": "foo"}`, &cfg, `missing c_list`)
70 }
71
72 type testTimeDurationConfig struct {
73 D ConfigTimeDuration
74 }
75
76 func (s *configSuite) TestReadConfigTimeDuration(c *C) {
77 buf := bytes.NewBufferString(`{"d": "2s"}`)
78 var cfg testTimeDurationConfig
79 err := ReadConfig(buf, &cfg)
80 c.Assert(err, IsNil)
81 c.Check(cfg.D.TimeDuration(), Equals, 2*time.Second)
82 }
83
84 func (s *configSuite) TestReadConfigTimeDurationErrors(c *C) {
85 var cfg testTimeDurationConfig
86 checkError(c, `{"d": 1}`, &cfg, "d:.*type string")
87 checkError(c, `{"d": "2"}`, &cfg, "d:.*missing unit.*")
88 }
89
90 type testHostPortConfig struct {
91 H ConfigHostPort
92 }
93
94 func (s *configSuite) TestReadConfigHostPort(c *C) {
95 buf := bytes.NewBufferString(`{"h": "127.0.0.1:9999"}`)
96 var cfg testHostPortConfig
97 err := ReadConfig(buf, &cfg)
98 c.Assert(err, IsNil)
99 c.Check(cfg.H.HostPort(), Equals, "127.0.0.1:9999")
100 }
101
102 func (s *configSuite) TestReadConfigHostPortErrors(c *C) {
103 var cfg testHostPortConfig
104 checkError(c, `{"h": 1}`, &cfg, "h:.*type string")
105 checkError(c, `{"h": ""}`, &cfg, "h: missing port in address")
106 }
107
108 type testQueueSizeConfig struct {
109 QS ConfigQueueSize
110 }
111
112 func (s *configSuite) TestReadConfigQueueSize(c *C) {
113 buf := bytes.NewBufferString(`{"qS": 1}`)
114 var cfg testQueueSizeConfig
115 err := ReadConfig(buf, &cfg)
116 c.Assert(err, IsNil)
117 c.Check(cfg.QS.QueueSize(), Equals, uint(1))
118 }
119
120 func (s *configSuite) TestReadConfigQueueSizeErrors(c *C) {
121 var cfg testQueueSizeConfig
122 checkError(c, `{"qS": "x"}`, &cfg, "qS: .*type uint")
123 checkError(c, `{"qS": 0}`, &cfg, "qS: queue size should be > 0")
124 }
125
126 func (s *configSuite) TestLoadFile(c *C) {
127 tmpDir := c.MkDir()
128 d, err := LoadFile("", tmpDir)
129 c.Check(err, IsNil)
130 c.Check(d, IsNil)
131 fullPath := filepath.Join(tmpDir, "example.file")
132 err = ioutil.WriteFile(fullPath, []byte("Example"), os.ModePerm)
133 c.Assert(err, IsNil)
134 d, err = LoadFile("example.file", tmpDir)
135 c.Check(err, IsNil)
136 c.Check(string(d), Equals, "Example")
137 d, err = LoadFile(fullPath, tmpDir)
138 c.Check(err, IsNil)
139 c.Check(string(d), Equals, "Example")
140 }
141
142 func (s *configSuite) TestReadFiles(c *C) {
143 tmpDir := c.MkDir()
144 cfg1Path := filepath.Join(tmpDir, "cfg1.json")
145 err := ioutil.WriteFile(cfg1Path, []byte(`{"a": 42}`), os.ModePerm)
146 c.Assert(err, IsNil)
147 cfg2Path := filepath.Join(tmpDir, "cfg2.json")
148 err = ioutil.WriteFile(cfg2Path, []byte(`{"b": "x", "c_list": ["y", "z"]}`), os.ModePerm)
149 c.Assert(err, IsNil)
150 var cfg testConfig1
151 err = ReadFiles(&cfg, cfg1Path, cfg2Path)
152 c.Assert(err, IsNil)
153 c.Check(cfg.A, Equals, 42)
154 c.Check(cfg.B, Equals, "x")
155 c.Check(cfg.C, DeepEquals, []string{"y", "z"})
156 }
157
158 func (s *configSuite) TestReadFilesErrors(c *C) {
159 var cfg testConfig1
160 err := ReadFiles(1)
161 c.Check(err, ErrorMatches, `destConfig not \*struct`)
162 err = ReadFiles(&cfg, "non-existent")
163 c.Check(err, ErrorMatches, "no config to read")
164 err = ReadFiles(&cfg, "/root")
165 c.Check(err, ErrorMatches, ".*permission denied")
166 tmpDir := c.MkDir()
167 err = ReadFiles(&cfg, tmpDir)
168 c.Check(err, ErrorMatches, ".*is a directory")
169 brokenCfgPath := filepath.Join(tmpDir, "b.json")
170 err = ioutil.WriteFile(brokenCfgPath, []byte(`{"a"-`), os.ModePerm)
171 c.Assert(err, IsNil)
172 err = ReadFiles(&cfg, brokenCfgPath)
173 c.Check(err, NotNil)
174 }
175
176 type testConfig2 struct {
177 A int
178 B string
179 C []string `json:"c_list"`
180 D ConfigTimeDuration
181 }
182
183 func (s *configSuite) TestReadFilesDefaults(c *C) {
184 var cfg testConfig2
185 tmpDir := c.MkDir()
186 emptyCfgPath := filepath.Join(tmpDir, "e.json")
187 err := ioutil.WriteFile(emptyCfgPath, []byte("{}"), os.ModePerm)
188 c.Assert(err, IsNil)
189 err = ReadFilesDefaults(&cfg, map[string]interface{}{
190 "a": 42,
191 "b": "foo",
192 "c_list": []string{"bar", "baz"},
193 "d": "3s",
194 }, emptyCfgPath)
195 c.Check(err, IsNil)
196 c.Check(cfg.A, Equals, 42)
197 c.Check(cfg.B, Equals, "foo")
198 c.Check(cfg.C, DeepEquals, []string{"bar", "baz"})
199 c.Check(cfg.D.TimeDuration(), Equals, 3*time.Second)
200 }
201
202 func (s *configSuite) TestReadFilesDefaultsError(c *C) {
203 var cfg testConfig2
204 err := ReadFilesDefaults(&cfg, map[string]interface{}{
205 "a": make(chan int),
206 })
207 c.Assert(err, NotNil)
208 }
209
210 type B struct {
211 BFld int
212 }
213
214 type A struct {
215 AFld int
216 B
217 private int
218 }
219
220 func (s *configSuite) TestTraverseStruct(c *C) {
221 var a A
222 var i = 1
223 for destField := range traverseStruct(reflect.ValueOf(&a).Elem()) {
224 *(destField.dest.(*int)) = i
225 i++
226 }
227 c.Check(a, DeepEquals, A{1, B{2}, 0})
228 }
229
230 func (s *configSuite) TestCompareConfig(c *C) {
231 var cfg1 = testConfig2{
232 A: 1,
233 B: "xyz",
234 C: []string{"a", "b"},
235 D: ConfigTimeDuration{200 * time.Millisecond},
236 }
237 var cfg2 = testConfig2{
238 A: 1,
239 B: "xyz",
240 C: []string{"a", "b"},
241 D: ConfigTimeDuration{200 * time.Millisecond},
242 }
243 _, err := CompareConfig(cfg1, &cfg2)
244 c.Check(err, ErrorMatches, `config1 not \*struct`)
245 _, err = CompareConfig(&cfg1, cfg2)
246 c.Check(err, ErrorMatches, `config2 not \*struct`)
247 _, err = CompareConfig(&cfg1, &testConfig1{})
248 c.Check(err, ErrorMatches, `config1 and config2 don't have the same type`)
249
250 res, err := CompareConfig(&cfg1, &cfg2)
251 c.Assert(err, IsNil)
252 c.Check(res, IsNil)
253
254 cfg1.B = "zyx"
255 cfg2.C = []string{"a", "B"}
256 cfg2.D = ConfigTimeDuration{205 * time.Millisecond}
257
258 res, err = CompareConfig(&cfg1, &cfg2)
259 c.Assert(err, IsNil)
260 c.Check(res, DeepEquals, []string{"b", "c_list", "d"})
261
262 }
263
264 type testConfig3 struct {
265 A bool
266 B string
267 C []string `json:"c_list"`
268 D ConfigTimeDuration `help:"duration"`
269 E ConfigHostPort
270 F string
271 }
272
273 type configFlagsSuite struct{}
274
275 var _ = Suite(&configFlagsSuite{})
276
277 func (s *configFlagsSuite) SetUpTest(c *C) {
278 flag.CommandLine = flag.NewFlagSet("cmd", flag.PanicOnError)
279 // supress outputs
280 flag.Usage = func() { flag.PrintDefaults() }
281 flag.CommandLine.SetOutput(ioutil.Discard)
282 }
283
284 func (s *configFlagsSuite) TestReadUsingFlags(c *C) {
285 os.Args = []string{"cmd", "-a=1", "-b=foo", "-c_list", `["x","y"]`, "-d", "10s", "-e=localhost:80"}
286 var cfg testConfig3
287 p := make(map[string]json.RawMessage)
288 err := readUsingFlags(p, reflect.ValueOf(&cfg))
289 c.Assert(err, IsNil)
290 c.Check(p, DeepEquals, map[string]json.RawMessage{
291 "a": json.RawMessage("true"),
292 "b": json.RawMessage(`"foo"`),
293 "c_list": json.RawMessage(`["x","y"]`),
294 "d": json.RawMessage(`"10s"`),
295 "e": json.RawMessage(`"localhost:80"`),
296 })
297 }
298
299 func (s *configFlagsSuite) TestReadUsingFlagsBoolError(c *C) {
300 os.Args = []string{"cmd", "-a=zoo"}
301 var cfg testConfig3
302 p := make(map[string]json.RawMessage)
303 c.Check(func() { readUsingFlags(p, reflect.ValueOf(&cfg)) }, PanicMatches, ".*invalid boolean.*-a.*")
304 }
305
306 func (s *configFlagsSuite) TestReadFilesAndFlags(c *C) {
307 // test <flags> pseudo file
308 os.Args = []string{"cmd", "-b=x"}
309 tmpDir := c.MkDir()
310 cfgPath := filepath.Join(tmpDir, "cfg.json")
311 err := ioutil.WriteFile(cfgPath, []byte(`{"a": 42, "c_list": ["y", "z"]}`), os.ModePerm)
312 c.Assert(err, IsNil)
313 var cfg testConfig1
314 err = ReadFiles(&cfg, cfgPath, "<flags>")
315 c.Assert(err, IsNil)
316 c.Check(cfg.A, Equals, 42)
317 c.Check(cfg.B, Equals, "x")
318 c.Check(cfg.C, DeepEquals, []string{"y", "z"})
319 }
320
321 func (s *configFlagsSuite) TestReadFilesAndFlagsConfigAtSupport(c *C) {
322 // test <flags> pseudo file
323 tmpDir := c.MkDir()
324 cfgPath := filepath.Join(tmpDir, "cfg.json")
325 os.Args = []string{"cmd", "-a=42", fmt.Sprintf("-cfg@=%s", cfgPath)}
326 err := ioutil.WriteFile(cfgPath, []byte(`{"b": "x", "c_list": ["y", "z"]}`), os.ModePerm)
327 c.Assert(err, IsNil)
328 var cfg testConfig1
329 err = ReadFiles(&cfg, "<flags>")
330 c.Assert(err, IsNil)
331 c.Check(cfg.A, Equals, 42)
332 c.Check(cfg.B, Equals, "x")
333 c.Check(cfg.C, DeepEquals, []string{"y", "z"})
334 c.Check(flag.Lookup("cfg@").Value.String(), Equals, cfgPath)
335 }
336
337 func (s *configFlagsSuite) TestReadUsingFlagsHelp(c *C) {
338 os.Args = []string{"cmd", "-h"}
339 buf := bytes.NewBufferString("")
340 flag.CommandLine.Init("cmd", flag.ContinueOnError)
341 flag.CommandLine.SetOutput(buf)
342 var cfg testConfig3
343 p := map[string]json.RawMessage{
344 "d": json.RawMessage(`"2s"`),
345 }
346 readUsingFlags(p, reflect.ValueOf(&cfg))
347 c.Check(buf.String(), Matches, `(?s).*get config values from file.*duration.*`)
348 }
349
350 func (s *configFlagsSuite) TestReadUsingFlagsAlreadyParsed(c *C) {
351 os.Args = []string{"cmd"}
352 flag.Parse()
353 var cfg struct{}
354 p := make(map[string]json.RawMessage)
355 err := readUsingFlags(p, reflect.ValueOf(&cfg))
356 c.Assert(err, ErrorMatches, "too late, flags already parsed")
357 err = ReadFiles(&cfg, "<flags>")
358 c.Assert(err, ErrorMatches, "too late, flags already parsed")
359 IgnoreParsedFlags = true
360 defer func() {
361 IgnoreParsedFlags = false
362 }()
363 err = ReadFiles(&cfg, "<flags>")
364 c.Assert(err, IsNil)
365 }