-
Notifications
You must be signed in to change notification settings - Fork 191
/
encoding_test.go
77 lines (60 loc) · 1.7 KB
/
encoding_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
package jsonutil_test
import (
"bytes"
"strings"
"testing"
"github.com/gookit/goutil/jsonutil"
"github.com/gookit/goutil/testutil/assert"
)
func TestEncode(t *testing.T) {
bts, err := jsonutil.Encode(testUser)
assert.NoErr(t, err)
assert.Eq(t, `{"name":"inhere","age":200}`, string(bts))
bts, err = jsonutil.Encode(&testUser)
assert.NoErr(t, err)
assert.Eq(t, `{"name":"inhere","age":200}`, string(bts))
assert.Eq(t, `{"name":"inhere","age":200}`, jsonutil.MustString(testUser))
assert.Panics(t, func() {
jsonutil.MustString(invalid)
})
bts, err = jsonutil.Encode(&testUser)
assert.NoErr(t, err)
assert.Eq(t, `{"name":"inhere","age":200}`, string(bts))
}
func TestEncodeUnescapeHTML(t *testing.T) {
bts, err := jsonutil.EncodeUnescapeHTML(&testUser)
assert.NoErr(t, err)
assert.Eq(t, `{"name":"inhere","age":200}
`, string(bts))
_, err = jsonutil.EncodeUnescapeHTML(invalid)
assert.Err(t, err)
}
func TestEncodeToWriter(t *testing.T) {
buf := &bytes.Buffer{}
err := jsonutil.EncodeToWriter(testUser, buf)
assert.NoErr(t, err)
assert.Eq(t, `{"name":"inhere","age":200}
`, buf.String())
}
func TestDecode(t *testing.T) {
str := `{"name":"inhere","age":200}`
usr := &user{}
err := jsonutil.Decode([]byte(str), usr)
assert.NoErr(t, err)
assert.Eq(t, "inhere", usr.Name)
assert.Eq(t, 200, usr.Age)
}
func TestDecodeString(t *testing.T) {
str := `{"name":"inhere","age":200}`
usr := &user{}
err := jsonutil.DecodeString(str, usr)
assert.NoErr(t, err)
assert.Eq(t, "inhere", usr.Name)
assert.Eq(t, 200, usr.Age)
// DecodeReader
usr = &user{}
err = jsonutil.DecodeReader(strings.NewReader(str), usr)
assert.NoErr(t, err)
assert.Eq(t, "inhere", usr.Name)
assert.Eq(t, 200, usr.Age)
}