forked from pschou/go-json
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathautoconv_test.go
89 lines (77 loc) · 1.96 KB
/
autoconv_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
package json
import (
"fmt"
"strings"
"testing"
)
type QuotedVals struct {
IntQ int
BoolQ bool
}
func TestUnmarshalQuoted(t *testing.T) {
var quotedVals QuotedVals
jsonDec := NewDecoder(strings.NewReader(`{"IntQ":"1","BoolQ":"true"}`))
jsonDec.UseAutoConvert()
if err := jsonDec.Decode("edVals); err != nil {
t.Fatalf("Unmarshal: %v", err)
}
if quotedVals.IntQ != 1 || quotedVals.BoolQ != true {
t.Fatalf("Did not read QuotedVals")
}
}
type SliceVals struct {
Sub SliceValSub
Val []int
Vals []int
Bw []int
FV fancyVal
NI newInt
}
type SliceValSub struct {
Dat string
}
func TestUnmarshalSliceAutoConvertCustomType(t *testing.T) {
var Vals SliceVals
jsonDec := NewDecoder(strings.NewReader(`{"Sub":{"Dat":"hi"},"Val":"1","Vals":[1,2],"Bw":["1000000","1000000"],"FV":"lang","NI":"45"}`))
jsonDec.UseAutoConvert()
jsonDec.UseSlice()
if err := jsonDec.Decode(&Vals); err != nil {
t.Fatalf("Unmarshal: %v", err)
}
if Vals.Sub.Dat != "hi" || Vals.Val[0] != 1 || Vals.Vals[1] != 2 ||
Vals.Bw[1] != 1000000 || Vals.FV.dat != "lang" {
t.Fatalf("Did not read correctly")
}
data, _ := Marshal(Vals)
if string(data) != `{"Sub":{"Dat":"hi"},"Val":[1],"Vals":[1,2],"Bw":[1000000,1000000],"FV":"lang","NI":"test"}` {
t.Fatalf("Did not marshal correctly")
}
}
func TestUnmarshalIgnoreEmpty(t *testing.T) {
var Vals SliceVals
jsonDec := NewDecoder(strings.NewReader(`{"Sub":{"Dat":{ }}}`))
jsonDec.UseAutoConvert()
jsonDec.UseSlice()
jsonDec.IgnoreEmptyObject()
if err := jsonDec.Decode(&Vals); err != nil {
t.Fatalf("Unmarshal: %v", err)
}
}
type fancyVal struct {
dat string
}
func (f *fancyVal) UnmarshalText(text []byte) error {
f.dat = string(text)
return nil
}
func (f fancyVal) MarshalText() (text []byte, err error) {
return []byte(f.dat), nil
}
type newInt int
func (i newInt) UnmarshalText(text []byte) error {
i = 42
return nil
}
func (i newInt) MarshalText() (text []byte, err error) {
return []byte(fmt.Sprintf("test")), nil
}