-
Notifications
You must be signed in to change notification settings - Fork 2
/
encoder_config_test.go
80 lines (74 loc) · 1.93 KB
/
encoder_config_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
package jzon
import (
"reflect"
"testing"
"unsafe"
"github.com/stretchr/testify/require"
)
type testIntEncoder struct{}
func (*testIntEncoder) IsEmpty(ptr unsafe.Pointer) bool {
return *(*int)(ptr) == 1
}
func (*testIntEncoder) Encode(ptr unsafe.Pointer, s *Streamer, opts *EncOpts) {
s.Int(*(*int)(ptr) + 1)
}
func TestEncoderConfig_CustomConfig(t *testing.T) {
t.Run("int", func(t *testing.T) {
encCfg := NewEncoderConfig(&EncoderOption{
ValEncoders: map[reflect.Type]ValEncoder{
reflect.TypeOf(int(0)): (*testIntEncoder)(nil),
},
})
t.Run("value", func(t *testing.T) {
b, err := encCfg.Marshal(1)
require.NoError(t, err)
require.Equal(t, "2", string(b))
})
t.Run("pointer", func(t *testing.T) {
i := 1
b, err := encCfg.Marshal(&i)
require.NoError(t, err)
require.Equal(t, "2", string(b))
})
t.Run("struct", func(t *testing.T) {
t.Run("value", func(t *testing.T) {
type st struct {
I int `json:",omitempty"`
}
t.Run("zero", func(t *testing.T) {
b, err := encCfg.Marshal(st{})
require.NoError(t, err)
require.Equal(t, `{"I":1}`, string(b))
})
t.Run("empty", func(t *testing.T) {
b, err := encCfg.Marshal(st{I: 1})
require.NoError(t, err)
require.Equal(t, `{}`, string(b))
})
})
t.Run("pointer", func(t *testing.T) {
type st struct {
I *int `json:",omitempty"`
}
t.Run("nil", func(t *testing.T) {
b, err := encCfg.Marshal(st{})
require.NoError(t, err)
require.Equal(t, `{}`, string(b))
})
t.Run("zero", func(t *testing.T) {
i := 0
b, err := encCfg.Marshal(st{I: &i})
require.NoError(t, err)
require.Equal(t, `{"I":1}`, string(b))
})
t.Run("empty", func(t *testing.T) {
i := 1
b, err := encCfg.Marshal(st{I: &i})
require.NoError(t, err)
// pointer is not nil so it's not considered as empty
require.Equal(t, `{"I":2}`, string(b))
})
})
})
})
}