-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathsmapping_test.go
More file actions
1252 lines (1150 loc) · 27.3 KB
/
smapping_test.go
File metadata and controls
1252 lines (1150 loc) · 27.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
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 smapping
import (
"database/sql"
"encoding/json"
"fmt"
"strings"
"testing"
"time"
)
type source struct {
Label string `json:"label"`
Info string `json:"info"`
Version int `json:"version"`
Toki time.Time `json:"tomare"`
Addr *string `json:"address"`
}
type sink struct {
Label string
Info string
}
type differentSink struct {
DiffLabel string `json:"label"`
NiceInfo string `json:"info"`
Version string `json:"unversion"`
Toki time.Time `json:"doki"`
Addr *string `json:"address"`
}
type differentSourceSink struct {
Source source `json:"source"`
DiffSink differentSink `json:"differentSink"`
}
var toki = time.Date(2000, time.January, 1, 0, 0, 0, 0, time.UTC)
var hello = "hello異世界"
var sourceobj source = source{
Label: "source",
Info: "the origin",
Version: 1,
Toki: toki,
Addr: &hello,
}
func printIfNotExists(mapped Mapped, keys ...string) {
for _, key := range keys {
if _, ok := mapped[key]; !ok {
fmt.Println(key, ": not exists")
}
}
}
func ExampleMapFields() {
mapped := MapFields(sourceobj)
printIfNotExists(mapped, "Label", "Info", "Version")
// Output:
}
func ExampleMapTags_basic() {
ptrSourceObj := &sourceobj
maptags := MapTags(&ptrSourceObj, "json")
printIfNotExists(maptags, "label", "info", "version")
// Output:
}
func ExampleMapTags_nested() {
nestedSource := differentSourceSink{
Source: sourceobj,
DiffSink: differentSink{
DiffLabel: "nested diff",
NiceInfo: "nested info",
Version: "next version",
Toki: toki,
Addr: &hello,
},
}
// this part illustrates that MapTags or any other Map function
// accept arbitrary pointers to struct.
ptrNestedSource := &nestedSource
ptr2NestedSource := &ptrNestedSource
ptr3NestedSource := &ptr2NestedSource
nestedMap := MapTags(&ptr3NestedSource, "json")
for k, v := range nestedMap {
fmt.Println("top key:", k)
for kk, vv := range v.(Mapped) {
if vtime, ok := vv.(time.Time); ok {
fmt.Println(" nested:", kk, vtime.Format(time.RFC3339))
} else {
fmt.Println(" nested:", kk, vv)
}
}
fmt.Println()
}
// Unordered Output:
// top key: source
// nested: label source
// nested: info the origin
// nested: version 1
// nested: tomare 2000-01-01T00:00:00Z
// nested: address hello異世界
//
// top key: differentSink
// nested: label nested diff
// nested: info nested info
// nested: unversion next version
// nested: doki 2000-01-01T00:00:00Z
// nested: address hello異世界
}
type generalFields struct {
Name string `json:"name" api:"general_name"`
Rank string `json:"rank" api:"general_rank"`
Code int `json:"code" api:"general_code"`
nickname string // won't be mapped because not exported
}
func ExampleMapTags_twoTags() {
general := generalFields{
Name: "duran",
Rank: "private",
Code: 1337,
nickname: "drone",
}
mapjson := MapTags(&general, "json")
printIfNotExists(mapjson, "name", "rank", "code")
mapapi := MapTags(&general, "api")
printIfNotExists(mapapi, "general_name", "general_rank", "general_code")
// Output:
}
func ExampleMapTagsWithDefault() {
type higherCommon struct {
General generalFields `json:"general"`
Communality string `json:"common"`
Available bool `json:"available" api:"is_available"`
}
rawjson := []byte(`{
"general": {
name: "duran",
rank: "private",
code: 1337,
},
"common": "rare",
"available": true
}`)
hc := higherCommon{}
_ = json.Unmarshal(rawjson, &hc)
maptags := MapTagsWithDefault(&hc, "api", "json")
printIfNotExists(maptags, "available")
// Output: available : not exists
}
func ExampleFillStruct() {
mapped := MapFields(&sourceobj)
sinked := sink{}
err := FillStruct(&sinked, mapped)
if err != nil {
panic(err)
}
fmt.Println(sinked)
// Output: {source the origin}
}
func ExampleFillStructByTags() {
maptags := MapTags(&sourceobj, "json")
for k, v := range maptags {
if vt, ok := v.(time.Time); ok {
fmt.Printf("maptags[%s]: %s\n", k, vt.Format(time.RFC3339))
} else {
fmt.Printf("maptags[%s]: %v\n", k, v)
}
}
diffsink := differentSink{}
err := FillStructByTags(&diffsink, maptags, "json")
if err != nil {
panic(err)
}
fmt.Println(diffsink.DiffLabel)
fmt.Println(diffsink.NiceInfo)
fmt.Println(diffsink.Version)
fmt.Println(diffsink.Toki)
fmt.Println(*diffsink.Addr)
// Unordered Output:
// maptags[label]: source
// maptags[info]: the origin
// maptags[version]: 1
// maptags[tomare]: 2000-01-01T00:00:00Z
// maptags[address]: hello異世界
// source
// the origin
//
// 0001-01-01 00:00:00 +0000 UTC
// hello異世界
}
type RefLevel3 struct {
What string `json:"finally"`
}
type Level2 struct {
*RefLevel3 `json:"ref_level3"`
}
type Level1 struct {
Level2 `json:"level2"`
}
type TopLayer struct {
Level1 `json:"level1"`
}
type MadNest struct {
TopLayer `json:"top"`
}
var madnestStruct MadNest = MadNest{
TopLayer: TopLayer{
Level1: Level1{
Level2: Level2{
RefLevel3: &RefLevel3{
What: "matryoska",
},
},
},
},
}
func TestMapTags_nested(t *testing.T) {
madnestMap := MapTags(&madnestStruct, "json")
if len(madnestMap) != 1 {
t.Errorf("Got empty Mapped, expected 1")
return
}
top, ok := madnestMap["top"]
if !ok {
t.Errorf("Failed to get top field")
return
}
lv1, ok := top.(Mapped)["level1"]
if !ok {
t.Errorf("Failed to get level 1 field")
return
}
lv2, ok := lv1.(Mapped)["level2"]
if !ok {
t.Errorf("Failed to get level 2 field")
return
}
reflv3, ok := lv2.(Mapped)["ref_level3"]
if !ok {
t.Errorf("Failed to get ref level 3 field")
return
}
what, ok := reflv3.(Mapped)["finally"]
if !ok {
t.Errorf("Failed to get the inner ref level 3")
return
}
switch v := what.(type) {
case string:
theval := what.(string)
if theval != "matryoska" {
t.Errorf("Expected matryoska, got %s", theval)
}
default:
t.Errorf("Expected string, got %T", v)
}
}
func TestMappingNotStruct(t *testing.T) {
m := MapFields("")
if lenm := len(m); lenm != 0 {
t.Errorf("Expected 0 got map with length %d", lenm)
}
m["dummy"] = 11
m["will"] = "vanish"
m = MapTags(5, "dummy-tag")
if lenm := len(m); lenm != 0 {
t.Errorf("Expected 0 got map with length %d", lenm)
}
}
func FillStructNestedTest(bytag bool, t *testing.T) {
var madnestObj MadNest
var err error
if bytag {
madnestMap := MapTags(&madnestStruct, "json")
err = FillStructByTags(&madnestObj, madnestMap, "json")
} else {
madnestMap := MapFields(&madnestStruct)
err = FillStruct(&madnestObj, madnestMap)
}
if err != nil {
t.Errorf("%s", err.Error())
return
}
t.Logf("madnestObj %#v\n", madnestObj)
if madnestObj.TopLayer.Level1.Level2.RefLevel3.What != "matryoska" {
t.Errorf("Error: expected \"matroska\" got \"%s\"", madnestObj.Level1.Level2.RefLevel3.What)
}
}
func TestFillStructByTags_nested(t *testing.T) {
FillStructNestedTest(true, t)
}
func TestFillStruct_nested(t *testing.T) {
FillStructNestedTest(false, t)
}
func fillStructTime(bytag bool, t *testing.T) {
type timeMap struct {
Label string `json:"label"`
Time time.Time `json:"definedTime"`
PtrTime *time.Time `json:"ptrTime"`
}
now := time.Now()
obj := timeMap{Label: "test", Time: now, PtrTime: &now}
objTarget := timeMap{}
if bytag {
// jsbyte, err := json.Marshal(obj)
// if err != nil {
// t.Error(err)
// return
// }
// mapp := Mapped{}
// _ = json.Unmarshal(jsbyte, &mapp)
mapfield := MapTags(&obj, "json")
err := FillStructByTags(&objTarget, mapfield, "json")
if err != nil {
t.Error(err)
return
}
} else {
mapfield := MapFields(&obj)
t.Logf("mapfield: %#v\n", mapfield)
// jsbyte, err := json.Marshal(mapfield)
// if err != nil {
// t.Error(err)
// return
// }
// mapp := Mapped{}
// err = json.Unmarshal(jsbyte, &mapp)
// if err != nil {
// t.Error(err)
// return
// }
err := FillStruct(&objTarget, mapfield)
if err != nil {
t.Error(err)
return
}
}
if !objTarget.Time.Equal(obj.Time) {
t.Errorf("Error value conversion: %s not equal with %s",
objTarget.Time.Format(time.RFC3339),
obj.Time.Format(time.RFC3339),
)
return
}
if !objTarget.PtrTime.Equal(*(obj.PtrTime)) {
t.Errorf("Error value pointer time conversion: %s not equal with %s",
objTarget.PtrTime.Format(time.RFC3339),
obj.PtrTime.Format(time.RFC3339),
)
return
}
}
func TestFillStructByTags_time_conversion(t *testing.T) {
fillStructTime(true, t)
}
func TestFillStruct_time_conversion(t *testing.T) {
fillStructTime(false, t)
}
func ExampleMapTagsFlatten() {
type (
Last struct {
Final string `json:"final"`
Destination string
}
Lv3 struct {
Lv3Str string `json:"lv3str"`
*Last `json:"last"`
Lv3Dummy string
}
Lv2 struct {
Lv2Str string `json:"lv2str"`
Lv3 `json:"lv3"`
Lv2Dummy string
}
Lv1 struct {
Lv2
Lv1Str string `json:"lv1str"`
Lv1Dummy string
}
)
obj := Lv1{
Lv1Str: "level 1 string",
Lv1Dummy: "baka",
Lv2: Lv2{
Lv2Dummy: "bakabaka",
Lv2Str: "level 2 string",
Lv3: Lv3{
Lv3Dummy: "bakabakka",
Lv3Str: "level 3 string",
Last: &Last{
Final: "destination",
Destination: "overloop",
},
},
},
}
for k, v := range MapTagsFlatten(&obj, "json") {
fmt.Printf("key: %s, value: %v\n", k, v)
}
// Unordered Output:
// key: final, value: destination
// key: lv1str, value: level 1 string
// key: lv2str, value: level 2 string
// key: lv3str, value: level 3 string
}
func ExampleFillStructDeflate_fromJson() {
type (
nest2 struct {
N2FieldFloat float64 `json:"nested2_flt"`
N2FieldStr string `json:"nested2_str"`
}
nest1 struct {
N1FieldFloat float64 `json:"nested1_flt"`
N1FieldStr string `json:"nested1_str"`
Nest2 *nest2 `json:"nested2"`
}
outerobj struct {
FieldFloat float64 `json:"field_flt"`
FieldStr string `json:"field_str"`
Nest1 nest1 `json:"nested1"`
}
)
rawb := `
{
"field_str": "555",
"field_flt": 5,
"nested1_flt": 515,
"nested1_str": "515",
"nested2_flt": 525,
"nested2_str": "525"
}`
var m map[string]interface{}
fmt.Println(json.Unmarshal([]byte(rawb), &m))
var tgt outerobj
fmt.Println("error result fill struct deflate:", FillStructDeflate(&tgt, m, "json"))
fmt.Printf("%#v\n", tgt.FieldFloat)
fmt.Printf("%#v\n", tgt.FieldStr)
fmt.Printf("%#v\n", tgt.Nest1.N1FieldFloat)
fmt.Printf("%#v\n", tgt.Nest1.N1FieldStr)
fmt.Printf("%#v\n", tgt.Nest1.Nest2.N2FieldFloat)
fmt.Printf("%#v\n", tgt.Nest1.Nest2.N2FieldStr)
// Output:
// <nil>
// error result fill struct deflate: <nil>
// 5
// "555"
// 515
// "515"
// 525
// "525"
}
type dummyValues struct {
Int int
Int8 int8
Int16 int16
Int32 int32
Int64 int64
Uint uint
Uint8 uint8
Uint16 uint16
Uint32 uint32
Uint64 uint64
Float32 float32
Float64 float64
Bool bool
String string
Bytes []byte
sql.NullBool
sql.NullFloat64
sql.NullInt32
sql.NullInt64
sql.NullString
sql.NullTime
}
type dummyRow struct {
Values dummyValues
}
func (dr *dummyRow) Scan(dest ...interface{}) error {
for i, x := range dest {
switch x.(type) {
case *int:
dest[i] = &dr.Values.Int
case *int8:
dest[i] = &dr.Values.Int8
case *int16:
dest[i] = &dr.Values.Int16
case *int32:
dest[i] = &dr.Values.Int32
case *int64:
dest[i] = &dr.Values.Int64
case *uint:
dest[i] = &dr.Values.Uint
case *uint8:
dest[i] = &dr.Values.Uint8
case *uint16:
dest[i] = &dr.Values.Uint16
case *uint32:
dest[i] = &dr.Values.Uint32
case *uint64:
dest[i] = &dr.Values.Uint64
case *float32:
dest[i] = &dr.Values.Float32
case *float64:
dest[i] = &dr.Values.Float64
case *string:
dest[i] = &dr.Values.String
case *[]byte:
dest[i] = &dr.Values.Bytes
case *bool:
dest[i] = &dr.Values.Bool
case *sql.NullBool:
dest[i] = &dr.Values.NullBool
case *sql.NullFloat64:
dest[i] = &dr.Values.NullFloat64
case *sql.NullInt32:
dest[i] = &dr.Values.NullInt32
case *sql.NullInt64:
dest[i] = &dr.Values.NullInt64
case *sql.NullString:
dest[i] = &dr.Values.NullString
case *sql.NullTime:
dest[i] = &dr.Values.NullTime
}
}
return nil
}
func createDummyRow(destTime time.Time) *dummyRow {
return &dummyRow{
Values: dummyValues{
Int: -5,
Int8: -4,
Int16: -3,
Int32: -2,
Int64: -1,
Uint: 1,
Uint8: 2,
Uint16: 3,
Uint32: 4,
Uint64: 5,
Float32: 42.1,
Float64: 42.2,
Bool: true,
String: "hello 異世界",
Bytes: []byte("hello 異世界"),
NullBool: sql.NullBool{Bool: true, Valid: true},
NullFloat64: sql.NullFloat64{Float64: 42.2, Valid: true},
NullInt32: sql.NullInt32{Int32: 421, Valid: true},
NullInt64: sql.NullInt64{Int64: 422, Valid: true},
NullString: sql.NullString{String: "hello 異世界", Valid: true},
NullTime: sql.NullTime{Time: destTime, Valid: true},
},
}
}
func ExampleSQLScan_suppliedFields() {
currtime := time.Now()
dr := createDummyRow(currtime)
result := dummyValues{}
if err := SQLScan(dr, &result,
"", /* This is the tag, since we don't have so put it empty
to match the field name */
/* Below arguments are variadic and we only take several
fields from all available dummyValues */
"Int32", "Uint64", "Bool", "Bytes",
"NullString", "NullTime"); err != nil {
fmt.Println("Error happened!")
return
}
fmt.Printf("NullString is Valid? %t\n", result.NullString.Valid)
fmt.Printf("NullTime is Valid? %t\n", result.NullTime.Valid)
fmt.Printf("result.NullTime.Time.Equal(dr.Values.NullTime.Time)? %t\n",
result.NullTime.Time.Equal(dr.Values.NullTime.Time))
fmt.Printf("result.Uint64 == %d\n", result.Uint64)
// output:
// NullString is Valid? true
// NullTime is Valid? true
// result.NullTime.Time.Equal(dr.Values.NullTime.Time)? true
// result.Uint64 == 5
}
func ExampleSQLScan_allFields() {
currtime := time.Now()
dr := createDummyRow(currtime)
result := dummyValues{}
if err := SQLScan(dr, &result, ""); err != nil {
fmt.Println("Error happened!")
return
}
fmt.Printf("NullString is Valid? %t\n", result.NullString.Valid)
fmt.Printf("result.NullString is %s\n", result.NullString.String)
fmt.Printf("NullTime is Valid? %t\n", result.NullTime.Valid)
fmt.Printf("result.NullTime.Time.Equal(dr.Values.NullTime.Time)? %t\n",
result.NullTime.Time.Equal(dr.Values.NullTime.Time))
fmt.Printf("result.Uint64 == %d\n", result.Uint64)
// output:
// NullString is Valid? true
// result.NullString is hello 異世界
// NullTime is Valid? true
// result.NullTime.Time.Equal(dr.Values.NullTime.Time)? true
// result.Uint64 == 5
}
func notin(s string, pool ...string) bool {
for _, sp := range pool {
if strings.Contains(s, sp) {
return false
}
}
return true
}
func compareErrorReports(t *testing.T, msgs, errval, errfield []string) {
for _, msg := range msgs {
var (
field string
)
if notin(msg, errval...) {
t.Errorf("value '%s' not found", msg)
}
if field != "" && notin(field, errfield...) {
t.Errorf("field '%s' not found", field)
}
}
}
func TestBetterErrorReporting(t *testing.T) {
type SomeStruct struct {
Field1 int `errtag:"fieldint"`
Field2 bool `errtag:"fieldbol"`
Field3 string `errtag:"fieldstr"`
Field4 float64 `errtag:"fieldflo"`
Field5 struct{} `errtag:"fieldsru"`
}
field1 := "this should be int"
field2 := "this should be boolean"
field3 := "this is succesfully converted"
field4 := "this should be float64"
field5 := "this should be struct"
ssmap := Mapped{
"Field1": field1,
"Field2": field2,
"Field3": field3,
"Field4": field4,
"Field5": field5,
}
ss := SomeStruct{}
err := FillStruct(&ss, ssmap)
if err == nil {
t.Errorf("Error should not nil")
}
t.Log(err)
if ss.Field3 != field3 {
t.Errorf("ss.Field3 expected '%s' but got '%s'", field3, ss.Field3)
}
errmsg := err.Error()
msgs := strings.Split(errmsg, ",")
if len(msgs) == 0 {
t.Errorf("Error message should report more than one field, got 0 report")
}
errval := []string{field1, field2, field4, field5}
for i, s := range errval {
errval[i] = fmt.Sprintf(`"%s"`, s)
}
errfield := []string{"Field1", "Field2", "Field4", "Field5"}
compareErrorReports(t, msgs, errval, errfield)
ssmaptag := Mapped{
"fieldint": field1,
"fieldbol": field2,
"fieldstr": field3,
"fieldflo": field4,
"fieldsru": field5,
}
ss = SomeStruct{}
err = FillStructByTags(&ss, ssmaptag, "errtag")
if err == nil {
t.Errorf("Error should not nil")
}
if ss.Field3 != field3 {
t.Errorf("ss.Field3 expected '%s' but got '%s'", field3, ss.Field3)
}
errmsg = err.Error()
msgs = strings.Split(errmsg, ",")
if len(msgs) == 0 {
t.Errorf("Error message should report more than one field, got 0 report")
}
errfield = []string{"fieldint", "fieldbol", "fieldflo", "fieldsru"}
compareErrorReports(t, msgs, errval, errfield)
}
type (
embedObj struct {
FieldInt int `json:"fieldInt"`
FieldStr string `json:"fieldStr"`
FieldFloat float64 `json:"fieldFloat"`
}
embedEmbed struct {
Embed1 embedObj `json:"embed1"`
Embed2 *embedObj `json:"embed2"`
}
embedObjs struct {
Objs []*embedObj `json:"embeds"`
}
)
func TestNilValue(t *testing.T) {
obj := embedEmbed{
Embed1: embedObj{1, "one", 1.1},
}
objmap := MapTags(&obj, "json")
embed2 := embedEmbed{}
if err := FillStructByTags(&embed2, objmap, "json"); err != nil {
t.Errorf("objmap fill fail: %v", err)
}
if embed2.Embed2 != nil {
t.Errorf("Invalid nil conversion, value should be nil")
}
objmap = MapFields(&obj)
embed2 = embedEmbed{}
if err := FillStruct(&embed2, objmap); err != nil {
t.Errorf("objmap fields fill fail: %v", err)
}
if embed2.Embed2 != nil {
t.Errorf("Invalid nil conversion, value should be nil")
}
objsem := embedObjs{
Objs: []*embedObj{
{1, "one", 1.1},
{2, "two", 2.2},
nil,
{4, "four", 3.3},
{5, "five", 4.4},
},
}
objsmap := MapTags(&objsem, "json")
fillobjsem := embedObjs{}
if err := FillStructByTags(&fillobjsem, objsmap, "json"); err != nil {
t.Errorf("Should not fail: %v", err)
}
for i, obj := range fillobjsem.Objs {
if obj == nil && i != 2 {
t.Errorf("index %d of object value %v should not nil", i, obj)
} else if i == 2 && obj != nil {
t.Errorf("index 3 of object value %v should be nil", obj)
}
}
objsmap = MapFields(&objsem)
fillobjsem = embedObjs{}
if err := FillStruct(&fillobjsem, objsmap); err != nil {
t.Errorf("Should not fail: %v", err)
}
for i, obj := range fillobjsem.Objs {
if obj == nil && i != 2 {
t.Errorf("index %d of object value %v should not nil", i, obj)
} else if i == 2 && obj != nil {
t.Errorf("index 3 of object value %v should be nil", obj)
}
}
}
func eq(a, b *embedObj) bool {
if a == nil || b == nil {
return false
}
return a.FieldFloat == b.FieldFloat && a.FieldInt == b.FieldInt &&
a.FieldStr == b.FieldStr
}
func arrobj(t *testing.T) {
objsem := embedObjs{
Objs: []*embedObj{
{1, "one", 1.1},
{2, "two", 2.2},
nil,
{4, "four", 3.3},
{5, "five", 4.4},
},
}
maptag := MapTags(&objsem, "json")
embedstf, ok := maptag["embeds"].([]interface{})
if !ok {
t.Fatalf("Wrong type, %#v", maptag["embeds"])
}
if len(embedstf) != len(objsem.Objs) {
t.Fatalf("len(embedstf) expected %d got %d\n", len(objsem.Objs), len(embedstf))
}
for i, emtf := range embedstf {
if i == 2 && emtf != nil {
t.Errorf("%v expected nil, got empty value\n", emtf)
continue
}
if i == 2 {
continue
}
emtfmap, ok := emtf.(Mapped)
// emtf2, ok := emtf.(*embedObj)
if !ok {
t.Errorf("Cannot cast to Mapped %#v\n", emtf)
continue
}
emtf2 := &embedObj{}
if err := FillStructByTags(emtf2, emtfmap, "json"); err != nil {
t.Error(err)
}
if !eq(emtf2, objsem.Objs[i]) && i != 2 {
t.Errorf("embedObj (%#v) at index %d got wrong value, expect (%#v)",
emtf2, i, objsem.Objs[i])
}
}
// raw of mapped case
rawtfobj := Mapped{
"embeds": []Mapped{
{"fieldInt": 1, "fieldStr": "one", "fieldFloat": 1.1},
{"fieldInt": 2, "fieldStr": "two", "fieldFloat": 2.2},
nil,
{"fieldInt": 4, "fieldStr": "four", "fieldFloat": 4.4},
{"fieldInt": 5, "fieldStr": "five", "fieldFloat": 5.5},
},
}
expectedVals := []*embedObj{
{1, "one", 1.1},
{2, "two", 2.2},
nil,
{4, "four", 4.4},
{5, "five", 5.5},
}
testit := func(raw Mapped) {
newemb := embedObjs{}
err := FillStructByTags(&newemb, rawtfobj, "json")
if err != nil {
t.Error(err)
}
t.Logf("%#v\n", newemb)
newemblen := len(newemb.Objs)
exptlen := len(expectedVals)
if newemblen != exptlen {
t.Fatalf("New len got %d, expected %d", newemblen, exptlen)
}
for i, ob := range newemb.Objs {
if i == 2 && ob != nil {
t.Errorf("%v expected nil, got empty value\n", ob)
continue
}
if i != 2 && !eq(ob, expectedVals[i]) {
t.Errorf("embedObj (%#v) at index %d got wrong value, expect (%#v)",
ob, i, expectedVals[i])
}
}
}
testit(rawtfobj)
// case of actual object
rawtfobj = Mapped{
"embeds": []*embedObj{
{1, "one", 1.1},
{2, "two", 2.2},
nil,
{4, "four", 4.4},
{5, "five", 5.5},
},
}
testit(rawtfobj)
}
func arrvalues(t *testing.T) {
type (
ArrInt []int
MyArrInt struct {
ArrInt `json:"array_int"`
}
APint []*int
MPint struct {
APint `json:"ptarr_int"`
}
APfloat []*float32
MPfloat struct {
APfloat `json:"ptarr_float"`
}
)
initobj := MyArrInt{
ArrInt: []int{1, 2, 3, 4, 5},
}
minitobj := MapTags(&initobj, "json")
arintminit, ok := minitobj["array_int"].([]interface{})
if !ok {
t.Errorf("failed to cast %#v\n", minitobj["array_int"])
return
}
t.Logf("arrintminit %#v\n", arintminit)
rawminit := Mapped{
"array_int": []int{5, 4, 3, 2, 1},
}
var rinit MyArrInt
if err := FillStructByTags(&rinit, rawminit, "json"); err != nil {
t.Error(err)
}
t.Logf("rinit %#v\n", rinit)
a := new(int)
b := new(int)
c := new(int)
d := new(int)
e := new(int)
*a = 11
*b = 22
*c = 33
*d = 44
*e = 55
pinitobj := MPint{
APint: []*int{a, b, nil, c, d, e},
}
mapinit := MapTags(&pinitobj, "json")
rawpinit, ok := mapinit["ptarr_int"].([]interface{})
if !ok {
t.Errorf("failed conv %#v\n", mapinit["ptrarr_int"])
}
t.Logf("rawpinit %#v\n", rawpinit)
for i, rp := range rawpinit {
if i == 2 && rp != nil {
t.Errorf("rp should be nil, %#v\n", rp)
}
if i == 2 {
continue
}
p, ok := rp.(int)
if !ok {
t.Errorf("failed cast, got %#v %T\n", rp, rp)
}
ptrop := pinitobj.APint[i]
if ptrop != nil && i != 2 && *ptrop != p {
t.Errorf("Wrong value at index %d, got %#v expected %#v",
i, p, *ptrop)
}
}
rawpinit2 := Mapped{
"ptarr_int": []interface{}{55, 44, nil, 33, 22, 11},
}
var pinit2 MPint
if err := FillStructByTags(&pinit2, rawpinit2, "json"); err != nil {
t.Error(err)
}
expt2 := []*int{e, d, nil, c, b, a}
t.Logf("pinit2 %#v\n", pinit2)
for i, rp := range pinit2.APint {
if i == 2 && rp != nil {