Repository navigation
Expand file tree
/
Copy pathfile_test.go
More file actions
668 lines (559 loc) · 17.3 KB
/
Copy pathfile_test.go
File metadata and controls
668 lines (559 loc) · 17.3 KB
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
// Copyright 2017 Unknwon
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
package ini
import (
"bytes"
"os"
"runtime"
"sort"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestEmpty(t *testing.T) {
f := Empty()
require.NotNil(t, f)
// Should only have the default section
assert.Len(t, f.Sections(), 1)
// Default section should not contain any key
assert.Len(t, f.Section("").Keys(), 0)
}
func TestFile_NewSection(t *testing.T) {
f := Empty()
require.NotNil(t, f)
sec, err := f.NewSection("author")
require.NoError(t, err)
require.NotNil(t, sec)
assert.Equal(t, "author", sec.Name())
assert.Equal(t, []string{DefaultSection, "author"}, f.SectionStrings())
t.Run("with duplicated name", func(t *testing.T) {
sec, err := f.NewSection("author")
require.NoError(t, err)
require.NotNil(t, sec)
// Does nothing if section already exists
assert.Equal(t, []string{DefaultSection, "author"}, f.SectionStrings())
})
t.Run("with empty string", func(t *testing.T) {
_, err := f.NewSection("")
require.Error(t, err)
})
}
func TestFile_NonUniqueSection(t *testing.T) {
t.Run("read and write non-unique sections", func(t *testing.T) {
f, err := LoadSources(LoadOptions{
AllowNonUniqueSections: true,
}, []byte(`[Interface]
Address = 192.168.2.1
PrivateKey = <server's privatekey>
ListenPort = 51820
[Peer]
PublicKey = <client's publickey>
AllowedIPs = 192.168.2.2/32
[Peer]
PublicKey = <client2's publickey>
AllowedIPs = 192.168.2.3/32`))
require.NoError(t, err)
require.NotNil(t, f)
sec, err := f.NewSection("Peer")
require.NoError(t, err)
require.NotNil(t, f)
_, _ = sec.NewKey("PublicKey", "<client3's publickey>")
_, _ = sec.NewKey("AllowedIPs", "192.168.2.4/32")
var buf bytes.Buffer
_, err = f.WriteTo(&buf)
require.NoError(t, err)
str := buf.String()
assert.Equal(t, `[Interface]
Address = 192.168.2.1
PrivateKey = <server's privatekey>
ListenPort = 51820
[Peer]
PublicKey = <client's publickey>
AllowedIPs = 192.168.2.2/32
[Peer]
PublicKey = <client2's publickey>
AllowedIPs = 192.168.2.3/32
[Peer]
PublicKey = <client3's publickey>
AllowedIPs = 192.168.2.4/32
`, str)
})
t.Run("delete non-unique section", func(t *testing.T) {
f, err := LoadSources(LoadOptions{
AllowNonUniqueSections: true,
}, []byte(`[Interface]
Address = 192.168.2.1
PrivateKey = <server's privatekey>
ListenPort = 51820
[Peer]
PublicKey = <client's publickey>
AllowedIPs = 192.168.2.2/32
[Peer]
PublicKey = <client2's publickey>
AllowedIPs = 192.168.2.3/32
[Peer]
PublicKey = <client3's publickey>
AllowedIPs = 192.168.2.4/32
`))
require.NoError(t, err)
require.NotNil(t, f)
err = f.DeleteSectionWithIndex("Peer", 1)
require.NoError(t, err)
var buf bytes.Buffer
_, err = f.WriteTo(&buf)
require.NoError(t, err)
str := buf.String()
assert.Equal(t, `[Interface]
Address = 192.168.2.1
PrivateKey = <server's privatekey>
ListenPort = 51820
[Peer]
PublicKey = <client's publickey>
AllowedIPs = 192.168.2.2/32
[Peer]
PublicKey = <client3's publickey>
AllowedIPs = 192.168.2.4/32
`, str)
})
t.Run("delete all sections", func(t *testing.T) {
f := Empty(LoadOptions{
AllowNonUniqueSections: true,
})
require.NotNil(t, f)
_ = f.NewSections("Interface", "Peer", "Peer")
assert.Equal(t, []string{DefaultSection, "Interface", "Peer", "Peer"}, f.SectionStrings())
f.DeleteSection("Peer")
assert.Equal(t, []string{DefaultSection, "Interface"}, f.SectionStrings())
})
}
func TestFile_NewRawSection(t *testing.T) {
f := Empty()
require.NotNil(t, f)
sec, err := f.NewRawSection("comments", `1111111111111111111000000000000000001110000
111111111111111111100000000000111000000000`)
require.NoError(t, err)
require.NotNil(t, sec)
assert.Equal(t, "comments", sec.Name())
assert.Equal(t, []string{DefaultSection, "comments"}, f.SectionStrings())
assert.Equal(t, `1111111111111111111000000000000000001110000
111111111111111111100000000000111000000000`, f.Section("comments").Body())
t.Run("with duplicated name", func(t *testing.T) {
sec, err := f.NewRawSection("comments", `1111111111111111111000000000000000001110000`)
require.NoError(t, err)
require.NotNil(t, sec)
assert.Equal(t, []string{DefaultSection, "comments"}, f.SectionStrings())
// Overwrite previous existed section
assert.Equal(t, `1111111111111111111000000000000000001110000`, f.Section("comments").Body())
})
t.Run("with empty string", func(t *testing.T) {
_, err := f.NewRawSection("", "")
require.Error(t, err)
})
}
func TestFile_NewSections(t *testing.T) {
f := Empty()
require.NotNil(t, f)
assert.NoError(t, f.NewSections("package", "author"))
assert.Equal(t, []string{DefaultSection, "package", "author"}, f.SectionStrings())
t.Run("with duplicated name", func(t *testing.T) {
assert.NoError(t, f.NewSections("author", "features"))
// Ignore section already exists
assert.Equal(t, []string{DefaultSection, "package", "author", "features"}, f.SectionStrings())
})
t.Run("with empty string", func(t *testing.T) {
assert.Error(t, f.NewSections("", ""))
})
}
func TestFile_GetSection(t *testing.T) {
f, err := Load(fullConf)
require.NoError(t, err)
require.NotNil(t, f)
sec, err := f.GetSection("author")
require.NoError(t, err)
require.NotNil(t, sec)
assert.Equal(t, "author", sec.Name())
t.Run("section not exists", func(t *testing.T) {
_, err := f.GetSection("404")
require.Error(t, err)
})
}
func TestFile_HasSection(t *testing.T) {
f, err := Load(fullConf)
require.NoError(t, err)
require.NotNil(t, f)
sec := f.HasSection("author")
assert.True(t, sec)
t.Run("section not exists", func(t *testing.T) {
nonexistent := f.HasSection("404")
assert.False(t, nonexistent)
})
}
func TestFile_Section(t *testing.T) {
t.Run("get a section", func(t *testing.T) {
f, err := Load(fullConf)
require.NoError(t, err)
require.NotNil(t, f)
sec := f.Section("author")
require.NotNil(t, sec)
assert.Equal(t, "author", sec.Name())
t.Run("section not exists", func(t *testing.T) {
sec := f.Section("404")
require.NotNil(t, sec)
assert.Equal(t, "404", sec.Name())
})
})
t.Run("get default section in lower case with insensitive load", func(t *testing.T) {
f, err := InsensitiveLoad([]byte(`
[default]
NAME = ini
VERSION = v1`))
require.NoError(t, err)
require.NotNil(t, f)
assert.Equal(t, "ini", f.Section("").Key("name").String())
assert.Equal(t, "v1", f.Section("").Key("version").String())
})
t.Run("get sections after deletion", func(t *testing.T) {
f, err := Load([]byte(`
[RANDOM]
`))
require.NoError(t, err)
require.NotNil(t, f)
sectionNames := f.SectionStrings()
sort.Strings(sectionNames)
assert.Equal(t, []string{DefaultSection, "RANDOM"}, sectionNames)
for _, currentSection := range sectionNames {
f.DeleteSection(currentSection)
}
for sectionParam, expectedSectionName := range map[string]string{
"": DefaultSection,
"RANDOM": "RANDOM",
} {
sec := f.Section(sectionParam)
require.NotNil(t, sec)
assert.Equal(t, expectedSectionName, sec.Name())
}
})
}
func TestFile_Sections(t *testing.T) {
f, err := Load(fullConf)
require.NoError(t, err)
require.NotNil(t, f)
secs := f.Sections()
names := []string{DefaultSection, "author", "package", "package.sub", "features", "types", "array", "note", "comments", "string escapes", "advance"}
assert.Len(t, secs, len(names))
for i, name := range names {
assert.Equal(t, name, secs[i].Name())
}
}
func TestFile_ChildSections(t *testing.T) {
f, err := Load([]byte(`
[node]
[node.biz1]
[node.biz2]
[node.biz3]
[node.bizN]
`))
require.NoError(t, err)
require.NotNil(t, f)
children := f.ChildSections("node")
names := []string{"node.biz1", "node.biz2", "node.biz3", "node.bizN"}
assert.Len(t, children, len(names))
for i, name := range names {
assert.Equal(t, name, children[i].Name())
}
}
func TestFile_SectionStrings(t *testing.T) {
f, err := Load(fullConf)
require.NoError(t, err)
require.NotNil(t, f)
assert.Equal(t, []string{DefaultSection, "author", "package", "package.sub", "features", "types", "array", "note", "comments", "string escapes", "advance"}, f.SectionStrings())
}
func TestFile_DeleteSection(t *testing.T) {
t.Run("delete a section", func(t *testing.T) {
f := Empty()
require.NotNil(t, f)
_ = f.NewSections("author", "package", "features")
f.DeleteSection("features")
f.DeleteSection("")
assert.Equal(t, []string{"author", "package"}, f.SectionStrings())
})
t.Run("delete default section", func(t *testing.T) {
f := Empty()
require.NotNil(t, f)
f.Section("").Key("foo").SetValue("bar")
f.Section("section1").Key("key1").SetValue("value1")
f.DeleteSection("")
assert.Equal(t, []string{"section1"}, f.SectionStrings())
var buf bytes.Buffer
_, err := f.WriteTo(&buf)
require.NoError(t, err)
assert.Equal(t, `[section1]
key1 = value1
`, buf.String())
})
t.Run("delete a section with InsensitiveSections", func(t *testing.T) {
f := Empty(LoadOptions{InsensitiveSections: true})
require.NotNil(t, f)
_ = f.NewSections("author", "package", "features")
f.DeleteSection("FEATURES")
f.DeleteSection("")
assert.Equal(t, []string{"author", "package"}, f.SectionStrings())
})
}
func TestFile_Append(t *testing.T) {
f := Empty()
require.NotNil(t, f)
assert.NoError(t, f.Append(minimalConf, []byte(`
[author]
NAME = Unknwon`)))
t.Run("with bad input", func(t *testing.T) {
assert.Error(t, f.Append(123))
assert.Error(t, f.Append(minimalConf, 123))
})
}
func TestFile_WriteTo(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Skipping testing on Windows")
}
t.Run("write content to somewhere", func(t *testing.T) {
f, err := Load(fullConf)
require.NoError(t, err)
require.NotNil(t, f)
f.Section("author").Comment = `Information about package author
# Bio can be written in multiple lines.`
f.Section("author").Key("NAME").Comment = "This is author name"
_, _ = f.Section("note").NewBooleanKey("boolean_key")
_, _ = f.Section("note").NewKey("more", "notes")
var buf bytes.Buffer
_, err = f.WriteTo(&buf)
require.NoError(t, err)
golden := "testdata/TestFile_WriteTo.golden"
if *update {
require.NoError(t, os.WriteFile(golden, buf.Bytes(), 0644))
}
expected, err := os.ReadFile(golden)
require.NoError(t, err)
assert.Equal(t, string(expected), buf.String())
})
t.Run("support multiline comments", func(t *testing.T) {
f, err := Load([]byte(`
#
# general.domain
#
# Domain name of XX system.
domain = mydomain.com
`))
require.NoError(t, err)
f.Section("").Key("test").Comment = "Multiline\nComment"
var buf bytes.Buffer
_, err = f.WriteTo(&buf)
require.NoError(t, err)
assert.Equal(t, `#
# general.domain
#
# Domain name of XX system.
domain = mydomain.com
; Multiline
; Comment
test =
`, buf.String())
})
t.Run("keep leading and trailing spaces in value", func(t *testing.T) {
f, _ := Load([]byte(`[foo]
bar1 = ' val ue1 '
bar2 = """ val ue2 """
bar3 = " val ue3 "
`))
require.NotNil(t, f)
var buf bytes.Buffer
_, err := f.WriteTo(&buf)
require.NoError(t, err)
assert.Equal(t, `[foo]
bar1 = " val ue1 "
bar2 = " val ue2 "
bar3 = " val ue3 "
`, buf.String())
})
t.Run("keep trailing comments after last section on rewrite", func(t *testing.T) {
// Ansible blockinfile markers: # BEGIN before the section, # END after its keys.
src := `# BEGIN
[profile test]
sso_region = us-east-1
output = json
# END
`
f, err := Load([]byte(src))
require.NoError(t, err)
assert.Equal(t, "# BEGIN", f.Section("profile test").Comment)
assert.Equal(t, "# END", f.Section("profile test").TrailingComment)
_, err = f.NewSection("profile extra")
require.NoError(t, err)
f.Section("profile extra").Key("region").SetValue("us-west-2")
var buf bytes.Buffer
_, err = f.WriteTo(&buf)
require.NoError(t, err)
out := buf.String()
endIdx := strings.Index(out, "# END")
newIdx := strings.Index(out, "[profile extra]")
assert.True(t, endIdx >= 0 && newIdx > endIdx, "trailing # END should stay with the original section, got:\n%s", out)
assert.Contains(t, out, "[profile extra]")
})
}
func TestFile_WriteToIndentWithShadows(t *testing.T) {
f := Empty(LoadOptions{AllowShadows: true})
section, err := f.NewSection("FILTER")
require.NoError(t, err)
key, err := section.NewKey("whitelist_key", "_CMDLINE")
require.NoError(t, err)
require.NoError(t, key.AddShadow("_EXE"))
require.NoError(t, key.AddShadow("_HOSTNAME"))
var buf bytes.Buffer
_, err = f.WriteToIndent(&buf, " ")
require.NoError(t, err)
want := "[FILTER]" + LineBreak +
" whitelist_key = _CMDLINE" + LineBreak +
" whitelist_key = _EXE" + LineBreak +
" whitelist_key = _HOSTNAME" + LineBreak
assert.Equal(t, want, buf.String())
}
func TestFile_SaveTo(t *testing.T) {
f, err := Load(fullConf)
require.NoError(t, err)
require.NotNil(t, f)
assert.NoError(t, f.SaveTo("testdata/conf_out.ini"))
assert.NoError(t, f.SaveToIndent("testdata/conf_out.ini", "\t"))
}
func TestFile_WriteToWithOutputDelimiter(t *testing.T) {
f, err := LoadSources(LoadOptions{
KeyValueDelimiterOnWrite: "->",
}, []byte(`[Others]
Cities = HangZhou|Boston
Visits = 1993-10-07T20:17:05Z, 1993-10-07T20:17:05Z
Years = 1993,1994
Numbers = 10010,10086
Ages = 18,19
Populations = 12345678,98765432
Coordinates = 192.168,10.11
Flags = true,false
Note = Hello world!`))
require.NoError(t, err)
require.NotNil(t, f)
var actual bytes.Buffer
var expected = []byte(`[Others]
Cities -> HangZhou|Boston
Visits -> 1993-10-07T20:17:05Z, 1993-10-07T20:17:05Z
Years -> 1993,1994
Numbers -> 10010,10086
Ages -> 18,19
Populations -> 12345678,98765432
Coordinates -> 192.168,10.11
Flags -> true,false
Note -> Hello world!
`)
_, err = f.WriteTo(&actual)
require.NoError(t, err)
assert.Equal(t, expected, actual.Bytes())
}
// Inspired by https://github.com/go-ini/ini/issues/207
func TestReloadAfterShadowLoad(t *testing.T) {
f, err := ShadowLoad([]byte(`
[slice]
v = 1
v = 2
v = 3
`))
require.NoError(t, err)
require.NotNil(t, f)
assert.Equal(t, []string{"1", "2", "3"}, f.Section("slice").Key("v").ValueWithShadows())
require.NoError(t, f.Reload())
assert.Equal(t, []string{"1", "2", "3"}, f.Section("slice").Key("v").ValueWithShadows())
}
func TestFile_WriteTo_ValueRoundTrip(t *testing.T) {
t.Run("values survive the default reader byte-for-byte", func(t *testing.T) {
bt := "`"
cases := []struct {
name string
val string
}{
// Surrounded by matching quotes: the reader would unquote these.
{"double-quoted", `"quoted"`},
{"single-quoted", `'quoted'`},
{"double-quoted empty", `""`},
{"single-quoted empty", `''`},
{"double-quoted spaces", `"a b"`},
{"single-quoted spaces", `'a b'`},
{"double-quoted number", `"123"`},
{"single-quoted number", `'123'`},
{"double-quoted equals", `"a=b"`},
// Leading/trailing spaces around an inner quote break "..." wrapping.
{"space then quote", ` "x" `},
{"quote then space", `"abc `},
// A value opening with """ would be read as a multi-line wrapper.
{"triple-quote wrapped", `"""abc"""`},
{"triple-quote prefix", `"""abc`},
{"four quotes", `""""`},
// No-regression: already-safe values must round-trip unchanged.
{"plain", "some value"},
{"inner quote", `a"b`},
{"quoted list", `"one", "two"`},
{"trailing space", "abc "},
{"three quotes", `"""`},
{"backtick", "a" + bt + "b"},
}
for _, c := range cases {
cfg := Empty()
cfg.Section("").Key("k").SetValue(c.val)
var buf bytes.Buffer
_, err := cfg.WriteTo(&buf)
require.NoError(t, err, c.name)
rc, err := Load(buf.Bytes())
require.NoError(t, err, "%s: reload of %q", c.name, buf.String())
got := rc.Section("").Key("k").String()
assert.Equal(t, c.val, got,
"%s: round-trip mismatch\n in: %q\n ser: %q\n out: %q",
c.name, c.val, buf.String(), got)
}
})
t.Run("safe values are not over-quoted", func(t *testing.T) {
bt := "`"
cases := map[string]string{
"some value": "k = some value\n",
`a"b`: "k = a\"b\n",
`"one", "two"`: "k = \"one\", \"two\"\n",
"a" + bt + "b": "k = \"\"\"a" + bt + "b\"\"\"\n",
}
for val, want := range cases {
cfg := Empty()
cfg.Section("").Key("k").SetValue(val)
var buf bytes.Buffer
_, err := cfg.WriteTo(&buf)
require.NoError(t, err, val)
assert.Equal(t, want, buf.String(), "value %q serialized form", val)
}
})
t.Run("PreserveSurroundedQuote keeps quoted values as they are", func(t *testing.T) {
const data = "DefaultTimezone = \"GMT+01 (Amsterdam, Berlin, Rome)\"\n"
opts := LoadOptions{PreserveSurroundedQuote: true}
cfg, err := LoadSources(opts, []byte(data))
require.NoError(t, err)
var buf bytes.Buffer
_, err = cfg.WriteTo(&buf)
require.NoError(t, err)
assert.Equal(t, data, buf.String())
rc, err := LoadSources(opts, buf.Bytes())
require.NoError(t, err)
assert.Equal(t, `"GMT+01 (Amsterdam, Berlin, Rome)"`, rc.Section("").Key("DefaultTimezone").String())
})
}