-
-
Notifications
You must be signed in to change notification settings - Fork 529
/
encode_test.go
1343 lines (1222 loc) · 30.4 KB
/
encode_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
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package toml
import (
"bytes"
"encoding/json"
"fmt"
"math"
"net"
"os"
"strconv"
"strings"
"testing"
"time"
)
func TestEncodeRoundTrip(t *testing.T) {
type Config struct {
Age int
Cats []string
Pi float64
Perfection []int
DOB time.Time
Ipaddress net.IP
}
var inputs = Config{
Age: 13,
Cats: []string{"one", "two", "three"},
Pi: 3.145,
Perfection: []int{11, 2, 3, 4},
DOB: time.Now(),
Ipaddress: net.ParseIP("192.168.59.254"),
}
var (
firstBuffer bytes.Buffer
secondBuffer bytes.Buffer
outputs Config
)
err := NewEncoder(&firstBuffer).Encode(inputs)
if err != nil {
t.Fatal(err)
}
_, err = Decode(firstBuffer.String(), &outputs)
if err != nil {
t.Logf("Could not decode:\n%s\n", firstBuffer.String())
t.Fatal(err)
}
err = NewEncoder(&secondBuffer).Encode(outputs)
if err != nil {
t.Fatal(err)
}
if firstBuffer.String() != secondBuffer.String() {
t.Errorf("%s\n\nIS NOT IDENTICAL TO\n\n%s", firstBuffer.String(), secondBuffer.String())
}
out, err := Marshal(inputs)
if err != nil {
t.Fatal(err)
}
if firstBuffer.String() != string(out) {
t.Errorf("%s\n\nIS NOT IDENTICAL TO\n\n%s", firstBuffer.String(), string(out))
}
}
func TestEncodeArrayHashWithNormalHashOrder(t *testing.T) {
type Alpha struct {
V int
}
type Beta struct {
V int
}
type Conf struct {
V int
A Alpha
B []Beta
}
val := Conf{
V: 1,
A: Alpha{2},
B: []Beta{{3}},
}
expected := "V = 1\n\n[A]\n V = 2\n\n[[B]]\n V = 3\n"
encodeExpected(t, "array hash with normal hash order", val, expected, nil)
}
func TestEncodeOmitEmptyStruct(t *testing.T) {
type (
T struct{ Int int }
Tpriv struct {
Int int
private int
}
Ttime struct {
Time time.Time
}
)
tests := []struct {
in any
want string
}{
{struct {
F T `toml:"f,omitempty"`
}{}, ""},
{struct {
F T `toml:"f,omitempty"`
}{T{1}}, "[f]\n Int = 1"},
{struct {
F Tpriv `toml:"f,omitempty"`
}{}, ""},
{struct {
F Tpriv `toml:"f,omitempty"`
}{Tpriv{1, 0}}, "[f]\n Int = 1"},
// Private field being set also counts as "not empty".
{struct {
F Tpriv `toml:"f,omitempty"`
}{Tpriv{0, 1}}, "[f]\n Int = 0"},
// time.Time is common use case, so test that explicitly.
{struct {
F Ttime `toml:"t,omitempty"`
}{}, ""},
{struct {
F Ttime `toml:"t,omitempty"`
}{Ttime{time.Time{}.Add(1)}}, "[t]\n Time = 0001-01-01T00:00:00.000000001Z"},
// TODO: also test with MarshalText, MarshalTOML returning non-zero
// value.
}
for _, tt := range tests {
t.Run("", func(t *testing.T) {
buf := new(bytes.Buffer)
err := NewEncoder(buf).Encode(tt.in)
if err != nil {
t.Fatal(err)
}
have := strings.TrimSpace(buf.String())
if have != tt.want {
t.Errorf("\nhave:\n%s\nwant:\n%s", have, tt.want)
}
})
}
}
func TestEncodeOmitEmpty(t *testing.T) {
type compareable struct {
Bool bool `toml:"bool,omitempty"`
}
type uncomparable struct {
Field []string `toml:"field,omitempty"`
}
type nestedUncomparable struct {
Field uncomparable `toml:"uncomparable,omitempty"`
Bool bool `toml:"bool,omitempty"`
}
type simple struct {
Bool bool `toml:"bool,omitempty"`
String string `toml:"string,omitempty"`
Array [0]byte `toml:"array,omitempty"`
Slice []int `toml:"slice,omitempty"`
Map map[string]string `toml:"map,omitempty"`
Time time.Time `toml:"time,omitempty"`
Compareable1 compareable `toml:"compareable1,omitempty"`
Compareable2 compareable `toml:"compareable2,omitempty"`
Uncomparable1 uncomparable `toml:"uncomparable1,omitempty"`
Uncomparable2 uncomparable `toml:"uncomparable2,omitempty"`
NestedUncomparable1 nestedUncomparable `toml:"nesteduncomparable1,omitempty"`
NestedUncomparable2 nestedUncomparable `toml:"nesteduncomparable2,omitempty"`
}
var v simple
encodeExpected(t, "fields with omitempty are omitted when empty", v, "", nil)
v = simple{
Bool: true,
String: " ",
Slice: []int{2, 3, 4},
Map: map[string]string{"foo": "bar"},
Time: time.Date(1985, 6, 18, 15, 16, 17, 0, time.UTC),
Compareable2: compareable{true},
Uncomparable2: uncomparable{[]string{"XXX"}},
NestedUncomparable1: nestedUncomparable{uncomparable{[]string{"XXX"}}, false},
NestedUncomparable2: nestedUncomparable{uncomparable{}, true},
}
expected := `bool = true
string = " "
slice = [2, 3, 4]
time = 1985-06-18T15:16:17Z
[map]
foo = "bar"
[compareable2]
bool = true
[uncomparable2]
field = ["XXX"]
[nesteduncomparable1]
[nesteduncomparable1.uncomparable]
field = ["XXX"]
[nesteduncomparable2]
bool = true
`
encodeExpected(t, "fields with omitempty are not omitted when non-empty",
v, expected, nil)
}
func TestEncodeOmitEmptyPointer(t *testing.T) {
type s struct {
String *string `toml:"string,omitempty"`
}
t.Run("nil pointers", func(t *testing.T) {
var v struct {
String *string `toml:"string,omitempty"`
Slice *[]string `toml:"slice,omitempty"`
Map *map[string]string `toml:"map,omitempty"`
Struct *s `toml:"struct,omitempty"`
}
encodeExpected(t, "", v, ``, nil)
})
t.Run("zero values", func(t *testing.T) {
str := ""
sl := []string{}
m := map[string]string{}
v := struct {
String *string `toml:"string,omitempty"`
Slice *[]string `toml:"slice,omitempty"`
Map *map[string]string `toml:"map,omitempty"`
Struct *s `toml:"struct,omitempty"`
}{&str, &sl, &m, &s{&str}}
want := `string = ""
slice = []
[map]
[struct]
string = ""
`
encodeExpected(t, "", v, want, nil)
})
t.Run("with values", func(t *testing.T) {
str := "XXX"
sl := []string{"XXX"}
m := map[string]string{"XXX": "XXX"}
v := struct {
String *string `toml:"string,omitempty"`
Slice *[]string `toml:"slice,omitempty"`
Map *map[string]string `toml:"map,omitempty"`
Struct *s `toml:"struct,omitempty"`
}{&str, &sl, &m, &s{&str}}
want := `string = "XXX"
slice = ["XXX"]
[map]
XXX = "XXX"
[struct]
string = "XXX"
`
encodeExpected(t, "", v, want, nil)
})
}
func TestEncodeOmitZero(t *testing.T) {
type simple struct {
Number int `toml:"number,omitzero"`
Real float64 `toml:"real,omitzero"`
Unsigned uint `toml:"unsigned,omitzero"`
}
value := simple{0, 0.0, uint(0)}
expected := ""
encodeExpected(t, "simple with omitzero, all zero", value, expected, nil)
value.Number = 10
value.Real = 20
value.Unsigned = 5
expected = `number = 10
real = 20.0
unsigned = 5
`
encodeExpected(t, "simple with omitzero, non-zero", value, expected, nil)
}
func TestEncodeOmitemptyEmptyName(t *testing.T) {
type simple struct {
S []int `toml:",omitempty"`
}
v := simple{[]int{1, 2, 3}}
expected := "S = [1, 2, 3]\n"
encodeExpected(t, "simple with omitempty, no name, non-empty field",
v, expected, nil)
}
func TestEncodeAnonymousStruct(t *testing.T) {
type Inner struct{ N int }
type inner struct{ B int }
type Embedded struct {
Inner1 Inner
Inner2 Inner
}
type Outer0 struct {
Inner
inner
}
type Outer1 struct {
Inner `toml:"inner"`
inner `toml:"innerb"`
}
type Outer3 struct {
Embedded
}
v0 := Outer0{Inner{3}, inner{4}}
expected := "N = 3\nB = 4\n"
encodeExpected(t, "embedded anonymous untagged struct", v0, expected, nil)
v1 := Outer1{Inner{3}, inner{4}}
expected = "[inner]\n N = 3\n\n[innerb]\n B = 4\n"
encodeExpected(t, "embedded anonymous tagged struct", v1, expected, nil)
v3 := Outer3{Embedded: Embedded{Inner{3}, Inner{4}}}
expected = "[Inner1]\n N = 3\n\n[Inner2]\n N = 4\n"
encodeExpected(t, "embedded anonymous multiple fields", v3, expected, nil)
}
func TestEncodeAnonymousStructPointerField(t *testing.T) {
type Inner struct{ N int }
type Outer0 struct{ *Inner }
type Outer1 struct {
*Inner `toml:"inner"`
}
v0 := Outer0{}
expected := ""
encodeExpected(t, "nil anonymous untagged struct pointer field", v0, expected, nil)
v0 = Outer0{&Inner{3}}
expected = "N = 3\n"
encodeExpected(t, "non-nil anonymous untagged struct pointer field", v0, expected, nil)
v1 := Outer1{}
expected = ""
encodeExpected(t, "nil anonymous tagged struct pointer field", v1, expected, nil)
v1 = Outer1{&Inner{3}}
expected = "[inner]\n N = 3\n"
encodeExpected(t, "non-nil anonymous tagged struct pointer field", v1, expected, nil)
}
func TestEncodeNestedAnonymousStructs(t *testing.T) {
type A struct{ A string }
type B struct{ B string }
type C struct{ C string }
type BC struct {
B
C
}
type Outer struct {
A
BC
}
v := &Outer{
A: A{
A: "a",
},
BC: BC{
B: B{
B: "b",
},
C: C{
C: "c",
},
},
}
expected := "A = \"a\"\nB = \"b\"\nC = \"c\"\n"
encodeExpected(t, "nested anonymous untagged structs", v, expected, nil)
}
type InnerForNextTest struct{ N int }
func (InnerForNextTest) F() {}
func (InnerForNextTest) G() {}
func TestEncodeAnonymousNoStructField(t *testing.T) {
type Inner interface{ F() }
type inner interface{ G() }
type IntS []int
type intS []int
type Outer0 struct {
Inner
inner
IntS
intS
}
v0 := Outer0{
Inner: InnerForNextTest{3},
inner: InnerForNextTest{4},
IntS: []int{5, 6},
intS: []int{7, 8},
}
expected := "IntS = [5, 6]\n\n[Inner]\n N = 3\n"
encodeExpected(t, "non struct anonymous field", v0, expected, nil)
}
func TestEncodeIgnoredFields(t *testing.T) {
type simple struct {
Number int `toml:"-"`
}
value := simple{}
expected := ""
encodeExpected(t, "ignored field", value, expected, nil)
}
func TestEncodeNaN(t *testing.T) {
s1 := struct {
Nan float64 `toml:"nan"`
Inf float64 `toml:"inf"`
}{math.NaN(), math.Inf(1)}
s2 := struct {
Nan float32 `toml:"nan"`
Inf float32 `toml:"inf"`
}{float32(math.NaN()), float32(math.Inf(-1))}
encodeExpected(t, "", s1, "nan = nan\ninf = inf\n", nil)
encodeExpected(t, "", s2, "nan = nan\ninf = -inf\n", nil)
}
func TestEncodePrimitive(t *testing.T) {
type MyStruct struct {
Data Primitive
DataA int
DataB string
}
decodeAndEncode := func(toml string) string {
var s MyStruct
_, err := Decode(toml, &s)
if err != nil {
t.Fatal(err)
}
var buf bytes.Buffer
err = NewEncoder(&buf).Encode(s)
if err != nil {
t.Fatal(err)
}
return buf.String()
}
original := `DataA = 1
DataB = "bbb"
Data = ["Foo", "Bar"]
`
reEncoded := decodeAndEncode(decodeAndEncode(original))
if reEncoded != original {
t.Errorf(
"re-encoded not the same as original\noriginal: %q\nre-encoded: %q",
original, reEncoded)
}
}
func TestEncodeError(t *testing.T) {
tests := []struct {
in any
wantErr string
}{
{make(chan int), "unsupported type for key '': chan"},
{struct{ C complex128 }{0}, "unsupported type: complex128"},
{[]complex128{0}, "unsupported type: complex128"},
}
for _, tt := range tests {
t.Run("", func(t *testing.T) {
err := NewEncoder(os.Stderr).Encode(tt.in)
if err == nil {
t.Fatal("err is nil")
}
if !errorContains(err, tt.wantErr) {
t.Errorf("wrong error\nhave: %q\nwant: %q", err, tt.wantErr)
}
})
}
}
type (
sound struct{ S string }
food struct{ F []string }
fun func()
cplx complex128
ints []int
sound2 struct{ S string }
food2 struct{ F []string }
fun2 func()
cplx2 complex128
ints2 []int
)
// This is intentionally wrong (pointer receiver)
func (s *sound) MarshalText() ([]byte, error) { return []byte(s.S), nil }
func (f food) MarshalText() ([]byte, error) { return []byte(strings.Join(f.F, ", ")), nil }
func (f fun) MarshalText() ([]byte, error) { return []byte("why would you do this?"), nil }
func (c cplx) MarshalText() ([]byte, error) {
cplx := complex128(c)
return []byte(fmt.Sprintf("(%f+%fi)", real(cplx), imag(cplx))), nil
}
func intsValue(is []int) []byte {
var buf bytes.Buffer
buf.WriteByte('<')
for i, v := range is {
if i > 0 {
buf.WriteByte(',')
}
buf.WriteString(strconv.Itoa(v))
}
buf.WriteByte('>')
return buf.Bytes()
}
func (is *ints) MarshalText() ([]byte, error) {
if is == nil {
return []byte("[]"), nil
}
return intsValue(*is), nil
}
func (s *sound2) MarshalTOML() ([]byte, error) { return []byte("\"" + s.S + "\""), nil }
func (f food2) MarshalTOML() ([]byte, error) {
return []byte("[\"" + strings.Join(f.F, "\", \"") + "\"]"), nil
}
func (f fun2) MarshalTOML() ([]byte, error) { return []byte("\"why would you do this?\""), nil }
func (c cplx2) MarshalTOML() ([]byte, error) {
cplx := complex128(c)
return []byte(fmt.Sprintf("\"(%f+%fi)\"", real(cplx), imag(cplx))), nil
}
func (is *ints2) MarshalTOML() ([]byte, error) {
// MarshalTOML must quote by self
if is == nil {
return []byte(`"[]"`), nil
}
return []byte(fmt.Sprintf(`"%s"`, intsValue(*is))), nil
}
func TestEncodeTextMarshaler(t *testing.T) {
x := struct {
Name string
Labels map[string]string
Sound sound
Sound2 *sound
Food food
Food2 *food
Complex cplx
Fun fun
Ints ints
Ints2 *ints2
}{
Name: "Goblok",
Sound: sound{"miauw"},
Sound2: &sound{"miauw"},
Labels: map[string]string{
"type": "cat",
"color": "black",
},
Food: food{[]string{"chicken", "fish"}},
Food2: &food{[]string{"chicken", "fish"}},
Complex: complex(42, 666),
Fun: func() { panic("x") },
Ints: ints{1, 2, 3, 4},
Ints2: &ints2{1, 2, 3, 4},
}
var buf bytes.Buffer
if err := NewEncoder(&buf).Encode(&x); err != nil {
t.Fatal(err)
}
want := `Name = "Goblok"
Sound = "miauw"
Sound2 = "miauw"
Food = "chicken, fish"
Food2 = "chicken, fish"
Complex = "(42.000000+666.000000i)"
Fun = "why would you do this?"
Ints = "<1,2,3,4>"
Ints2 = "<1,2,3,4>"
[Labels]
color = "black"
type = "cat"
`
if buf.String() != want {
t.Error("\n" + buf.String())
}
}
func TestEncodeTOMLMarshaler(t *testing.T) {
x := struct {
Name string
Labels map[string]string
Sound sound2
Sound2 *sound2
Food food2
Food2 *food2
Complex cplx2
Fun fun2
}{
Name: "Goblok",
Sound: sound2{"miauw"},
Sound2: &sound2{"miauw"},
Labels: map[string]string{
"type": "cat",
"color": "black",
},
Food: food2{[]string{"chicken", "fish"}},
Food2: &food2{[]string{"chicken", "fish"}},
Complex: complex(42, 666),
Fun: func() { panic("x") },
}
var buf bytes.Buffer
if err := NewEncoder(&buf).Encode(x); err != nil {
t.Fatal(err)
}
want := `Name = "Goblok"
Sound2 = "miauw"
Food = ["chicken", "fish"]
Food2 = ["chicken", "fish"]
Complex = "(42.000000+666.000000i)"
Fun = "why would you do this?"
[Labels]
color = "black"
type = "cat"
[Sound]
S = "miauw"
`
if buf.String() != want {
t.Error("\n" + buf.String())
}
}
type (
retNil1 string
retNil2 string
)
func (r retNil1) MarshalText() ([]byte, error) { return nil, nil }
func (r retNil2) MarshalTOML() ([]byte, error) { return nil, nil }
func TestEncodeEmpty(t *testing.T) {
t.Run("text", func(t *testing.T) {
var (
s struct{ Text retNil1 }
buf bytes.Buffer
)
err := NewEncoder(&buf).Encode(s)
if err == nil {
t.Fatalf("no error, but expected an error; output:\n%s", buf.String())
}
if buf.String() != "" {
t.Error("\n" + buf.String())
}
})
t.Run("toml", func(t *testing.T) {
var (
s struct{ Text retNil2 }
buf bytes.Buffer
)
err := NewEncoder(&buf).Encode(s)
if err == nil {
t.Fatalf("no error, but expected an error; output:\n%s", buf.String())
}
if buf.String() != "" {
t.Error("\n" + buf.String())
}
})
}
// Would previously fail on 32bit architectures; can test with:
//
// GOARCH=386 go test -c && ./toml.test
// GOARCH=arm GOARM=7 go test -c && qemu-arm ./toml.test
func TestEncode32bit(t *testing.T) {
type Inner struct {
A, B, C string
}
type Outer struct{ Inner }
encodeExpected(t, "embedded anonymous untagged struct",
Outer{Inner{"a", "b", "c"}},
"A = \"a\"\nB = \"b\"\nC = \"c\"\n",
nil)
}
// Skip invalid types if it has toml:"-"
//
// https://github.com/BurntSushi/toml/issues/345
func TestEncodeSkipInvalidType(t *testing.T) {
buf := new(bytes.Buffer)
err := NewEncoder(buf).Encode(struct {
Str string `toml:"str"`
Arr []func() `toml:"-"`
Map map[string]any `toml:"-"`
Func func() `toml:"-"`
}{
Str: "a",
Arr: []func(){func() {}},
Map: map[string]any{"f": func() {}},
Func: func() {},
})
if err != nil {
t.Fatal(err)
}
have := buf.String()
want := "str = \"a\"\n"
if have != want {
t.Errorf("\nwant: %q\nhave: %q\n", want, have)
}
}
func TestEncodeDuration(t *testing.T) {
tests := []time.Duration{
0,
time.Second,
time.Minute,
time.Hour,
248*time.Hour + 45*time.Minute + 24*time.Second,
12345678 * time.Nanosecond,
12345678 * time.Second,
4*time.Second + 2*time.Nanosecond,
}
for _, tt := range tests {
encodeExpected(t, tt.String(),
struct{ Dur time.Duration }{Dur: tt},
fmt.Sprintf("Dur = %q", tt), nil)
}
}
type jsonT struct {
Num json.Number
NumP *json.Number
Arr []json.Number
ArrP []*json.Number
Tbl map[string]json.Number
TblP map[string]*json.Number
}
var (
n2, n4, n6 = json.Number("2"), json.Number("4"), json.Number("6")
f2, f4, f6 = json.Number("2.2"), json.Number("4.4"), json.Number("6.6")
)
func TestEncodeJSONNumber(t *testing.T) {
tests := []struct {
in jsonT
want string
}{
{jsonT{}, "Num = 0"},
{jsonT{
Num: "1",
NumP: &n2,
Arr: []json.Number{"3"},
ArrP: []*json.Number{&n4},
Tbl: map[string]json.Number{"k1": "5"},
TblP: map[string]*json.Number{"k2": &n6}}, `
Num = 1
NumP = 2
Arr = [3]
ArrP = [4]
[Tbl]
k1 = 5
[TblP]
k2 = 6
`},
{jsonT{
Num: "1.1",
NumP: &f2,
Arr: []json.Number{"3.3"},
ArrP: []*json.Number{&f4},
Tbl: map[string]json.Number{"k1": "5.5"},
TblP: map[string]*json.Number{"k2": &f6}}, `
Num = 1.1
NumP = 2.2
Arr = [3.3]
ArrP = [4.4]
[Tbl]
k1 = 5.5
[TblP]
k2 = 6.6
`},
}
for _, tt := range tests {
t.Run("", func(t *testing.T) {
var buf bytes.Buffer
err := NewEncoder(&buf).Encode(tt.in)
if err != nil {
t.Fatal(err)
}
have := strings.TrimSpace(buf.String())
want := strings.ReplaceAll(strings.TrimSpace(tt.want), "\t", "")
if have != want {
t.Errorf("\nwant:\n%s\nhave:\n%s\n", want, have)
}
})
}
}
func TestEncode(t *testing.T) {
type (
Embedded struct {
Int int `toml:"_int"`
}
NonStruct int
MyInt int
)
date := time.Date(2014, 5, 11, 19, 30, 40, 0, time.UTC)
dateStr := "2014-05-11T19:30:40Z"
tests := map[string]struct {
input any
wantOutput string
wantError error
}{
"bool field": {
input: struct {
BoolTrue bool
BoolFalse bool
}{true, false},
wantOutput: "BoolTrue = true\nBoolFalse = false\n",
},
"int fields": {
input: struct {
Int int
Int8 int8
Int16 int16
Int32 int32
Int64 int64
}{1, 2, 3, 4, 5},
wantOutput: "Int = 1\nInt8 = 2\nInt16 = 3\nInt32 = 4\nInt64 = 5\n",
},
"uint fields": {
input: struct {
Uint uint
Uint8 uint8
Uint16 uint16
Uint32 uint32
Uint64 uint64
}{1, 2, 3, 4, 5},
wantOutput: "Uint = 1\nUint8 = 2\nUint16 = 3\nUint32 = 4" +
"\nUint64 = 5\n",
},
"float fields": {
input: struct {
Float32 float32
Float64 float64
}{1.5, 2.5},
wantOutput: "Float32 = 1.5\nFloat64 = 2.5\n",
},
"string field": {
input: struct{ String string }{"foo"},
wantOutput: "String = \"foo\"\n",
},
"string field with \\n escape": {
input: struct{ String string }{"foo\n"},
wantOutput: "String = \"foo\\n\"\n",
},
"string field and unexported field": {
input: struct {
String string
unexported int
}{"foo", 0},
wantOutput: "String = \"foo\"\n",
},
"datetime field in UTC": {
input: struct{ Date time.Time }{date},
wantOutput: fmt.Sprintf("Date = %s\n", dateStr),
},
"datetime field as primitive": {
// Using a map here to fail if isStructOrMap() returns true for
// time.Time.
input: map[string]any{
"Date": date,
"Int": 1,
},
wantOutput: fmt.Sprintf("Date = %s\nInt = 1\n", dateStr),
},
"array fields": {
input: struct {
IntArray0 [0]int
IntArray3 [3]int
}{[0]int{}, [3]int{1, 2, 3}},
wantOutput: "IntArray0 = []\nIntArray3 = [1, 2, 3]\n",
},
"slice fields": {
input: struct{ IntSliceNil, IntSlice0, IntSlice3 []int }{
nil, []int{}, []int{1, 2, 3},
},
wantOutput: "IntSlice0 = []\nIntSlice3 = [1, 2, 3]\n",
},
"datetime slices": {
input: struct{ DatetimeSlice []time.Time }{
[]time.Time{date, date},
},
wantOutput: fmt.Sprintf("DatetimeSlice = [%s, %s]\n",
dateStr, dateStr),
},
"nested arrays and slices": {
input: struct {
SliceOfArrays [][2]int
ArrayOfSlices [2][]int
SliceOfArraysOfSlices [][2][]int
ArrayOfSlicesOfArrays [2][][2]int
SliceOfMixedArrays [][2]any
ArrayOfMixedSlices [2][]any
}{
[][2]int{{1, 2}, {3, 4}},
[2][]int{{1, 2}, {3, 4}},
[][2][]int{
{
{1, 2}, {3, 4},
},
{
{5, 6}, {7, 8},
},
},
[2][][2]int{
{
{1, 2}, {3, 4},
},
{
{5, 6}, {7, 8},
},
},
[][2]any{
{1, 2}, {"a", "b"},
},
[2][]any{
{1, 2}, {"a", "b"},
},
},
wantOutput: `SliceOfArrays = [[1, 2], [3, 4]]
ArrayOfSlices = [[1, 2], [3, 4]]
SliceOfArraysOfSlices = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
ArrayOfSlicesOfArrays = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
SliceOfMixedArrays = [[1, 2], ["a", "b"]]
ArrayOfMixedSlices = [[1, 2], ["a", "b"]]
`,
},
"empty slice": {
input: struct{ Empty []any }{[]any{}},
wantOutput: "Empty = []\n",
},
"(error) slice with element type mismatch (string and integer)": {
input: struct{ Mixed []any }{[]any{1, "a"}},
wantOutput: "Mixed = [1, \"a\"]\n",
},
"(error) slice with element type mismatch (integer and float)": {
input: struct{ Mixed []any }{[]any{1, 2.5}},
wantOutput: "Mixed = [1, 2.5]\n",
},
"slice with elems of differing Go types, same TOML types": {
input: struct {
MixedInts []any
MixedFloats []any
}{
[]any{
int(1), int8(2), int16(3), int32(4), int64(5),
uint(1), uint8(2), uint16(3), uint32(4), uint64(5),