forked from go-ini/ini
-
Notifications
You must be signed in to change notification settings - Fork 0
/
struct_test.go
906 lines (773 loc) · 22.6 KB
/
struct_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
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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
// Copyright 2014 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_test
import (
"bytes"
"fmt"
"strings"
"testing"
"time"
. "github.com/smartystreets/goconvey/convey"
"gopkg.in/ini.v1"
)
type testNested struct {
Cities []string `delim:"|"`
Visits []time.Time
Years []int
Numbers []int64
Ages []uint
Populations []uint64
Coordinates []float64
Flags []bool
Note string
Unused int `ini:"-"`
}
type TestEmbeded struct {
GPA float64
}
type testStruct struct {
Name string `ini:"NAME"`
Age int
Male bool
Money float64
Born time.Time
Time time.Duration `ini:"Duration"`
OldVersionTime time.Duration
Others testNested
OthersPtr *testNested
NilPtr *testNested
*TestEmbeded `ini:"grade"`
Unused int `ini:"-"`
Unsigned uint
Omitted bool `ini:"omitthis,omitempty"`
Shadows []string `ini:",allowshadow"`
ShadowInts []int `ini:"Shadows,allowshadow"`
BoolPtr *bool
BoolPtrNil *bool
FloatPtr *float64
FloatPtrNil *float64
IntPtr *int
IntPtrNil *int
UintPtr *uint
UintPtrNil *uint
StringPtr *string
StringPtrNil *string
TimePtr *time.Time
TimePtrNil *time.Time
DurationPtr *time.Duration
DurationPtrNil *time.Duration
}
type testInterface struct {
Address string
ListenPort int
PrivateKey string
}
type testPeer struct {
PublicKey string
PresharedKey string
AllowedIPs []string `delim:","`
}
type testNonUniqueSectionsStruct struct {
Interface testInterface
Peer []testPeer `ini:",nonunique"`
}
type BaseStruct struct {
Base bool
}
type testExtend struct {
BaseStruct `ini:",extends"`
Extend bool
}
const confDataStruct = `
NAME = Unknwon
Age = 21
Male = true
Money = 1.25
Born = 1993-10-07T20:17:05Z
Duration = 2h45m
OldVersionTime = 30
Unsigned = 3
omitthis = true
Shadows = 1, 2
Shadows = 3, 4
BoolPtr = false
FloatPtr = 0
IntPtr = 0
UintPtr = 0
StringPtr = ""
TimePtr = 0001-01-01T00:00:00Z
DurationPtr = 0s
[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!
[OthersPtr]
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!
[grade]
GPA = 2.8
[foo.bar]
Here = there
When = then
[extended]
Base = true
Extend = true
`
const confNonUniqueSectionDataStruct = `[Interface]
Address = 10.2.0.1/24
ListenPort = 34777
PrivateKey = privServerKey
[Peer]
PublicKey = pubClientKey
PresharedKey = psKey
AllowedIPs = 10.2.0.2/32,fd00:2::2/128
[Peer]
PublicKey = pubClientKey2
PresharedKey = psKey2
AllowedIPs = 10.2.0.3/32,fd00:2::3/128
`
type unsupport struct {
Byte byte
}
type unsupport2 struct {
Others struct {
Cities byte
}
}
type Unsupport3 struct {
Cities byte
}
type unsupport4 struct {
*Unsupport3 `ini:"Others"`
}
type defaultValue struct {
Name string
Age int
Male bool
Optional *bool
Money float64
Born time.Time
Cities []string
}
type fooBar struct {
Here, When string
}
const invalidDataConfStruct = `
Name =
Age = age
Male = 123
Money = money
Born = nil
Cities =
`
func Test_MapToStruct(t *testing.T) {
Convey("Map to struct", t, func() {
Convey("Map file to struct", func() {
ts := new(testStruct)
So(ini.MapTo(ts, []byte(confDataStruct)), ShouldBeNil)
So(ts.Name, ShouldEqual, "Unknwon")
So(ts.Age, ShouldEqual, 21)
So(ts.Male, ShouldBeTrue)
So(ts.Money, ShouldEqual, 1.25)
So(ts.Unsigned, ShouldEqual, 3)
t, err := time.Parse(time.RFC3339, "1993-10-07T20:17:05Z")
So(err, ShouldBeNil)
So(ts.Born.String(), ShouldEqual, t.String())
dur, err := time.ParseDuration("2h45m")
So(err, ShouldBeNil)
So(ts.Time.Seconds(), ShouldEqual, dur.Seconds())
So(ts.OldVersionTime*time.Second, ShouldEqual, 30*time.Second)
So(strings.Join(ts.Others.Cities, ","), ShouldEqual, "HangZhou,Boston")
So(ts.Others.Visits[0].String(), ShouldEqual, t.String())
So(fmt.Sprint(ts.Others.Years), ShouldEqual, "[1993 1994]")
So(fmt.Sprint(ts.Others.Numbers), ShouldEqual, "[10010 10086]")
So(fmt.Sprint(ts.Others.Ages), ShouldEqual, "[18 19]")
So(fmt.Sprint(ts.Others.Populations), ShouldEqual, "[12345678 98765432]")
So(fmt.Sprint(ts.Others.Coordinates), ShouldEqual, "[192.168 10.11]")
So(fmt.Sprint(ts.Others.Flags), ShouldEqual, "[true false]")
So(ts.Others.Note, ShouldEqual, "Hello world!")
So(ts.TestEmbeded.GPA, ShouldEqual, 2.8)
So(strings.Join(ts.OthersPtr.Cities, ","), ShouldEqual, "HangZhou,Boston")
So(ts.OthersPtr.Visits[0].String(), ShouldEqual, t.String())
So(fmt.Sprint(ts.OthersPtr.Years), ShouldEqual, "[1993 1994]")
So(fmt.Sprint(ts.OthersPtr.Numbers), ShouldEqual, "[10010 10086]")
So(fmt.Sprint(ts.OthersPtr.Ages), ShouldEqual, "[18 19]")
So(fmt.Sprint(ts.OthersPtr.Populations), ShouldEqual, "[12345678 98765432]")
So(fmt.Sprint(ts.OthersPtr.Coordinates), ShouldEqual, "[192.168 10.11]")
So(fmt.Sprint(ts.OthersPtr.Flags), ShouldEqual, "[true false]")
So(ts.OthersPtr.Note, ShouldEqual, "Hello world!")
So(ts.NilPtr, ShouldBeNil)
So(*ts.BoolPtr, ShouldEqual, false)
So(ts.BoolPtrNil, ShouldEqual, nil)
So(*ts.FloatPtr, ShouldEqual, 0)
So(ts.FloatPtrNil, ShouldEqual, nil)
So(*ts.IntPtr, ShouldEqual, 0)
So(ts.IntPtrNil, ShouldEqual, nil)
So(*ts.UintPtr, ShouldEqual, 0)
So(ts.UintPtrNil, ShouldEqual, nil)
So(*ts.StringPtr, ShouldEqual, "")
So(ts.StringPtrNil, ShouldEqual, nil)
So(*ts.TimePtr, ShouldNotEqual, nil)
So(ts.TimePtrNil, ShouldEqual, nil)
So(*ts.DurationPtr, ShouldEqual, 0)
So(ts.DurationPtrNil, ShouldEqual, nil)
})
Convey("Map section to struct", func() {
foobar := new(fooBar)
f, err := ini.Load([]byte(confDataStruct))
So(err, ShouldBeNil)
So(f.Section("foo.bar").MapTo(foobar), ShouldBeNil)
So(foobar.Here, ShouldEqual, "there")
So(foobar.When, ShouldEqual, "then")
})
Convey("Map to non-pointer struct", func() {
f, err := ini.Load([]byte(confDataStruct))
So(err, ShouldBeNil)
So(f, ShouldNotBeNil)
So(f.MapTo(testStruct{}), ShouldNotBeNil)
})
Convey("Map to unsupported type", func() {
f, err := ini.Load([]byte(confDataStruct))
So(err, ShouldBeNil)
So(f, ShouldNotBeNil)
f.NameMapper = func(raw string) string {
if raw == "Byte" {
return "NAME"
}
return raw
}
So(f.MapTo(&unsupport{}), ShouldNotBeNil)
So(f.MapTo(&unsupport2{}), ShouldNotBeNil)
So(f.MapTo(&unsupport4{}), ShouldNotBeNil)
})
Convey("Map to omitempty field", func() {
ts := new(testStruct)
So(ini.MapTo(ts, []byte(confDataStruct)), ShouldBeNil)
So(ts.Omitted, ShouldEqual, true)
})
Convey("Map with shadows", func() {
f, err := ini.LoadSources(ini.LoadOptions{AllowShadows: true}, []byte(confDataStruct))
So(err, ShouldBeNil)
ts := new(testStruct)
So(f.MapTo(ts), ShouldBeNil)
So(strings.Join(ts.Shadows, " "), ShouldEqual, "1 2 3 4")
So(fmt.Sprintf("%v", ts.ShadowInts), ShouldEqual, "[1 2 3 4]")
})
Convey("Map from invalid data source", func() {
So(ini.MapTo(&testStruct{}, "hi"), ShouldNotBeNil)
})
Convey("Map to wrong types and gain default values", func() {
f, err := ini.Load([]byte(invalidDataConfStruct))
So(err, ShouldBeNil)
t, err := time.Parse(time.RFC3339, "1993-10-07T20:17:05Z")
So(err, ShouldBeNil)
dv := &defaultValue{"Joe", 10, true, nil, 1.25, t, []string{"HangZhou", "Boston"}}
So(f.MapTo(dv), ShouldBeNil)
So(dv.Name, ShouldEqual, "Joe")
So(dv.Age, ShouldEqual, 10)
So(dv.Male, ShouldBeTrue)
So(dv.Money, ShouldEqual, 1.25)
So(dv.Born.String(), ShouldEqual, t.String())
So(strings.Join(dv.Cities, ","), ShouldEqual, "HangZhou,Boston")
})
Convey("Map to extended base", func() {
f, err := ini.Load([]byte(confDataStruct))
So(err, ShouldBeNil)
So(f, ShouldNotBeNil)
te := testExtend{}
So(f.Section("extended").MapTo(&te), ShouldBeNil)
So(te.Base, ShouldBeTrue)
So(te.Extend, ShouldBeTrue)
})
})
Convey("Map to struct in strict mode", t, func() {
f, err := ini.Load([]byte(`
name=bruce
age=a30`))
So(err, ShouldBeNil)
type Strict struct {
Name string `ini:"name"`
Age int `ini:"age"`
}
s := new(Strict)
So(f.Section("").StrictMapTo(s), ShouldNotBeNil)
})
Convey("Map slice in strict mode", t, func() {
f, err := ini.Load([]byte(`
names=alice, bruce`))
So(err, ShouldBeNil)
type Strict struct {
Names []string `ini:"names"`
}
s := new(Strict)
So(f.Section("").StrictMapTo(s), ShouldBeNil)
So(fmt.Sprint(s.Names), ShouldEqual, "[alice bruce]")
})
}
func Test_MapToStructNonUniqueSections(t *testing.T) {
Convey("Map to struct non unique", t, func() {
Convey("Map file to struct non unique", func() {
f, err := ini.LoadSources(ini.LoadOptions{AllowNonUniqueSections: true}, []byte(confNonUniqueSectionDataStruct))
So(err, ShouldBeNil)
ts := new(testNonUniqueSectionsStruct)
So(f.MapTo(ts), ShouldBeNil)
So(ts.Interface.Address, ShouldEqual, "10.2.0.1/24")
So(ts.Interface.ListenPort, ShouldEqual, 34777)
So(ts.Interface.PrivateKey, ShouldEqual, "privServerKey")
So(ts.Peer[0].PublicKey, ShouldEqual, "pubClientKey")
So(ts.Peer[0].PresharedKey, ShouldEqual, "psKey")
So(ts.Peer[0].AllowedIPs[0], ShouldEqual, "10.2.0.2/32")
So(ts.Peer[0].AllowedIPs[1], ShouldEqual, "fd00:2::2/128")
So(ts.Peer[1].PublicKey, ShouldEqual, "pubClientKey2")
So(ts.Peer[1].PresharedKey, ShouldEqual, "psKey2")
So(ts.Peer[1].AllowedIPs[0], ShouldEqual, "10.2.0.3/32")
So(ts.Peer[1].AllowedIPs[1], ShouldEqual, "fd00:2::3/128")
})
Convey("Map non unique section to struct", func() {
newPeer := new(testPeer)
newPeerSlice := make([]testPeer, 0)
f, err := ini.LoadSources(ini.LoadOptions{AllowNonUniqueSections: true}, []byte(confNonUniqueSectionDataStruct))
So(err, ShouldBeNil)
// try only first one
So(f.Section("Peer").MapTo(newPeer), ShouldBeNil)
So(newPeer.PublicKey, ShouldEqual, "pubClientKey")
So(newPeer.PresharedKey, ShouldEqual, "psKey")
So(newPeer.AllowedIPs[0], ShouldEqual, "10.2.0.2/32")
So(newPeer.AllowedIPs[1], ShouldEqual, "fd00:2::2/128")
// try all
So(f.Section("Peer").MapTo(&newPeerSlice), ShouldBeNil)
So(newPeerSlice[0].PublicKey, ShouldEqual, "pubClientKey")
So(newPeerSlice[0].PresharedKey, ShouldEqual, "psKey")
So(newPeerSlice[0].AllowedIPs[0], ShouldEqual, "10.2.0.2/32")
So(newPeerSlice[0].AllowedIPs[1], ShouldEqual, "fd00:2::2/128")
So(newPeerSlice[1].PublicKey, ShouldEqual, "pubClientKey2")
So(newPeerSlice[1].PresharedKey, ShouldEqual, "psKey2")
So(newPeerSlice[1].AllowedIPs[0], ShouldEqual, "10.2.0.3/32")
So(newPeerSlice[1].AllowedIPs[1], ShouldEqual, "fd00:2::3/128")
})
Convey("Map non unique sections with subsections to struct", func() {
iniFile, err := ini.LoadSources(ini.LoadOptions{AllowNonUniqueSections: true}, strings.NewReader(`
[Section]
FieldInSubSection = 1
FieldInSubSection2 = 2
FieldInSection = 3
[Section]
FieldInSubSection = 4
FieldInSubSection2 = 5
FieldInSection = 6
`))
So(err, ShouldBeNil)
type SubSection struct {
FieldInSubSection string `ini:"FieldInSubSection"`
}
type SubSection2 struct {
FieldInSubSection2 string `ini:"FieldInSubSection2"`
}
type Section struct {
SubSection `ini:"Section"`
SubSection2 `ini:"Section"`
FieldInSection string `ini:"FieldInSection"`
}
type File struct {
Sections []Section `ini:"Section,nonunique"`
}
f := new(File)
err = iniFile.MapTo(f)
So(err, ShouldBeNil)
So(f.Sections[0].FieldInSubSection, ShouldEqual, "1")
So(f.Sections[0].FieldInSubSection2, ShouldEqual, "2")
So(f.Sections[0].FieldInSection, ShouldEqual, "3")
So(f.Sections[1].FieldInSubSection, ShouldEqual, "4")
So(f.Sections[1].FieldInSubSection2, ShouldEqual, "5")
So(f.Sections[1].FieldInSection, ShouldEqual, "6")
})
})
}
func Test_ReflectFromStruct(t *testing.T) {
Convey("Reflect from struct", t, func() {
type Embeded struct {
Dates []time.Time `delim:"|" comment:"Time data"`
Places []string
Years []int
Numbers []int64
Ages []uint
Populations []uint64
Coordinates []float64
Flags []bool
None []int
}
type Author struct {
Name string `ini:"NAME"`
Male bool
Optional *bool
Age int `comment:"Author's age"`
Height uint
GPA float64
Date time.Time
NeverMind string `ini:"-"`
ignored string
*Embeded `ini:"infos" comment:"Embeded section"`
}
t, err := time.Parse(time.RFC3339, "1993-10-07T20:17:05Z")
So(err, ShouldBeNil)
a := &Author{"Unknwon", true, nil, 21, 100, 2.8, t, "", "ignored",
&Embeded{
[]time.Time{t, t},
[]string{"HangZhou", "Boston"},
[]int{1993, 1994},
[]int64{10010, 10086},
[]uint{18, 19},
[]uint64{12345678, 98765432},
[]float64{192.168, 10.11},
[]bool{true, false},
[]int{},
}}
cfg := ini.Empty()
So(ini.ReflectFrom(cfg, a), ShouldBeNil)
var buf bytes.Buffer
_, err = cfg.WriteTo(&buf)
So(err, ShouldBeNil)
So(buf.String(), ShouldEqual, `NAME = Unknwon
Male = true
Optional =
; Author's age
Age = 21
Height = 100
GPA = 2.8
Date = 1993-10-07T20:17:05Z
; Embeded section
[infos]
; Time data
Dates = 1993-10-07T20:17:05Z|1993-10-07T20:17:05Z
Places = HangZhou,Boston
Years = 1993,1994
Numbers = 10010,10086
Ages = 18,19
Populations = 12345678,98765432
Coordinates = 192.168,10.11
Flags = true,false
None =
`)
Convey("Reflect from non-point struct", func() {
So(ini.ReflectFrom(cfg, Author{}), ShouldNotBeNil)
})
Convey("Reflect from struct with omitempty", func() {
cfg := ini.Empty()
type SpecialStruct struct {
FirstName string `ini:"first_name"`
LastName string `ini:"last_name,omitempty"`
JustOmitMe string `ini:"omitempty"`
LastLogin time.Time `ini:"last_login,omitempty"`
LastLogin2 time.Time `ini:",omitempty"`
NotEmpty int `ini:"omitempty"`
Number int64 `ini:",omitempty"`
Ages uint `ini:",omitempty"`
Population uint64 `ini:",omitempty"`
Coordinate float64 `ini:",omitempty"`
Flag bool `ini:",omitempty"`
Note *string `ini:",omitempty"`
}
special := &SpecialStruct{
FirstName: "John",
LastName: "Doe",
NotEmpty: 9,
}
So(ini.ReflectFrom(cfg, special), ShouldBeNil)
var buf bytes.Buffer
_, err = cfg.WriteTo(&buf)
So(buf.String(), ShouldEqual, `first_name = John
last_name = Doe
omitempty = 9
`)
})
Convey("Reflect from struct with non-anonymous structure pointer", func() {
cfg := ini.Empty()
type Rpc struct {
Enable bool `ini:"enable"`
Type string `ini:"type"`
Address string `ini:"addr"`
Name string `ini:"name"`
}
type Cfg struct {
Rpc *Rpc `ini:"rpc"`
}
config := &Cfg{
Rpc: &Rpc{
Enable: true,
Type: "type",
Address: "address",
Name: "name",
},
}
So(cfg.ReflectFrom(config), ShouldBeNil)
var buf bytes.Buffer
_, err = cfg.WriteTo(&buf)
So(buf.String(), ShouldEqual, `[rpc]
enable = true
type = type
addr = address
name = name
`)
})
})
}
func Test_ReflectFromStructNonUniqueSections(t *testing.T) {
Convey("Reflect from struct with non unique sections", t, func() {
nonUnique := &testNonUniqueSectionsStruct{
Interface: testInterface{
Address: "10.2.0.1/24",
ListenPort: 34777,
PrivateKey: "privServerKey",
},
Peer: []testPeer{
{
PublicKey: "pubClientKey",
PresharedKey: "psKey",
AllowedIPs: []string{"10.2.0.2/32,fd00:2::2/128"},
},
{
PublicKey: "pubClientKey2",
PresharedKey: "psKey2",
AllowedIPs: []string{"10.2.0.3/32,fd00:2::3/128"},
},
},
}
cfg := ini.Empty(ini.LoadOptions{
AllowNonUniqueSections: true,
})
So(ini.ReflectFrom(cfg, nonUnique), ShouldBeNil)
var buf bytes.Buffer
_, err := cfg.WriteTo(&buf)
So(err, ShouldBeNil)
So(buf.String(), ShouldEqual, confNonUniqueSectionDataStruct)
// note: using ReflectFrom from should overwrite the existing sections
err = cfg.Section("Peer").ReflectFrom([]*testPeer{
{
PublicKey: "pubClientKey3",
PresharedKey: "psKey3",
AllowedIPs: []string{"10.2.0.4/32,fd00:2::4/128"},
},
{
PublicKey: "pubClientKey4",
PresharedKey: "psKey4",
AllowedIPs: []string{"10.2.0.5/32,fd00:2::5/128"},
},
})
So(err, ShouldBeNil)
buf = bytes.Buffer{}
_, err = cfg.WriteTo(&buf)
So(err, ShouldBeNil)
So(buf.String(), ShouldEqual, `[Interface]
Address = 10.2.0.1/24
ListenPort = 34777
PrivateKey = privServerKey
[Peer]
PublicKey = pubClientKey3
PresharedKey = psKey3
AllowedIPs = 10.2.0.4/32,fd00:2::4/128
[Peer]
PublicKey = pubClientKey4
PresharedKey = psKey4
AllowedIPs = 10.2.0.5/32,fd00:2::5/128
`)
// note: using ReflectFrom from should overwrite the existing sections
err = cfg.Section("Peer").ReflectFrom(&testPeer{
PublicKey: "pubClientKey5",
PresharedKey: "psKey5",
AllowedIPs: []string{"10.2.0.6/32,fd00:2::6/128"},
})
So(err, ShouldBeNil)
buf = bytes.Buffer{}
_, err = cfg.WriteTo(&buf)
So(err, ShouldBeNil)
So(buf.String(), ShouldEqual, `[Interface]
Address = 10.2.0.1/24
ListenPort = 34777
PrivateKey = privServerKey
[Peer]
PublicKey = pubClientKey5
PresharedKey = psKey5
AllowedIPs = 10.2.0.6/32,fd00:2::6/128
`)
})
}
// Inspired by https://github.com/go-ini/ini/issues/196
func TestMapToAndReflectFromStructWithShadows(t *testing.T) {
Convey("Map to struct and then reflect with shadows should generate original config content", t, func() {
type include struct {
Paths []string `ini:"path,omitempty,allowshadow"`
}
cfg, err := ini.LoadSources(ini.LoadOptions{
AllowShadows: true,
}, []byte(`
[include]
path = /tmp/gpm-profiles/test5.profile
path = /tmp/gpm-profiles/test1.profile`))
So(err, ShouldBeNil)
sec := cfg.Section("include")
inc := new(include)
err = sec.MapTo(inc)
So(err, ShouldBeNil)
err = sec.ReflectFrom(inc)
So(err, ShouldBeNil)
var buf bytes.Buffer
_, err = cfg.WriteTo(&buf)
So(err, ShouldBeNil)
So(buf.String(), ShouldEqual, `[include]
path = /tmp/gpm-profiles/test5.profile
path = /tmp/gpm-profiles/test1.profile
`)
Convey("Reflect from struct with shadows", func() {
cfg := ini.Empty(ini.LoadOptions{
AllowShadows: true,
})
type ShadowStruct struct {
StringArray []string `ini:"sa,allowshadow"`
EmptyStringArrat []string `ini:"empty,omitempty,allowshadow"`
Allowshadow []string `ini:"allowshadow,allowshadow"`
Dates []time.Time `ini:",allowshadow"`
Places []string `ini:",allowshadow"`
Years []int `ini:",allowshadow"`
Numbers []int64 `ini:",allowshadow"`
Ages []uint `ini:",allowshadow"`
Populations []uint64 `ini:",allowshadow"`
Coordinates []float64 `ini:",allowshadow"`
Flags []bool `ini:",allowshadow"`
None []int `ini:",allowshadow"`
}
shadow := &ShadowStruct{
StringArray: []string{"s1", "s2"},
Allowshadow: []string{"s3", "s4"},
Dates: []time.Time{time.Date(2020, 9, 12, 00, 00, 00, 651387237, time.UTC),
time.Date(2020, 9, 12, 00, 00, 00, 651387237, time.UTC)},
Places: []string{"HangZhou", "Boston"},
Years: []int{1993, 1994},
Numbers: []int64{10010, 10086},
Ages: []uint{18, 19},
Populations: []uint64{12345678, 98765432},
Coordinates: []float64{192.168, 10.11},
Flags: []bool{true, false},
None: []int{},
}
So(ini.ReflectFrom(cfg, shadow), ShouldBeNil)
var buf bytes.Buffer
_, err := cfg.WriteTo(&buf)
So(err, ShouldBeNil)
So(buf.String(), ShouldEqual, `sa = s1
sa = s2
allowshadow = s3
allowshadow = s4
Dates = 2020-09-12T00:00:00Z
Places = HangZhou
Places = Boston
Years = 1993
Years = 1994
Numbers = 10010
Numbers = 10086
Ages = 18
Ages = 19
Populations = 12345678
Populations = 98765432
Coordinates = 192.168
Coordinates = 10.11
Flags = true
Flags = false
None =
`)
})
})
}
type testMapper struct {
PackageName string
}
func Test_NameGetter(t *testing.T) {
Convey("Test name mappers", t, func() {
So(ini.MapToWithMapper(&testMapper{}, ini.TitleUnderscore, []byte("packag_name=ini")), ShouldBeNil)
cfg, err := ini.Load([]byte("PACKAGE_NAME=ini"))
So(err, ShouldBeNil)
So(cfg, ShouldNotBeNil)
cfg.NameMapper = ini.SnackCase
tg := new(testMapper)
So(cfg.MapTo(tg), ShouldBeNil)
So(tg.PackageName, ShouldEqual, "ini")
})
}
type testDurationStruct struct {
Duration time.Duration `ini:"Duration"`
}
func Test_Duration(t *testing.T) {
Convey("Duration less than 16m50s", t, func() {
ds := new(testDurationStruct)
So(ini.MapTo(ds, []byte("Duration=16m49s")), ShouldBeNil)
dur, err := time.ParseDuration("16m49s")
So(err, ShouldBeNil)
So(ds.Duration.Seconds(), ShouldEqual, dur.Seconds())
})
}
type Employer struct {
Name string
Title string
}
type Employers []*Employer
func (es Employers) ReflectINIStruct(f *ini.File) error {
for _, e := range es {
f.Section(e.Name).Key("Title").SetValue(e.Title)
}
return nil
}
// Inspired by https://github.com/go-ini/ini/issues/199
func Test_StructReflector(t *testing.T) {
Convey("Reflect with StructReflector interface", t, func() {
p := &struct {
FirstName string
Employer Employers
}{
FirstName: "Andrew",
Employer: []*Employer{
{
Name: `Employer "VMware"`,
Title: "Staff II Engineer",
},
{
Name: `Employer "EMC"`,
Title: "Consultant Engineer",
},
},
}
f := ini.Empty()
So(f.ReflectFrom(p), ShouldBeNil)
var buf bytes.Buffer
_, err := f.WriteTo(&buf)
So(err, ShouldBeNil)
So(buf.String(), ShouldEqual, `FirstName = Andrew
[Employer "VMware"]
Title = Staff II Engineer
[Employer "EMC"]
Title = Consultant Engineer
`)
})
}