-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcodec_test.go
105 lines (82 loc) · 1.85 KB
/
codec_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
package qstream
import (
"strconv"
"testing"
"github.com/stretchr/testify/assert"
"github.com/sirupsen/logrus"
)
var (
log = logrus.WithField("pkg", "qstream")
)
type SimpleData struct {
ID int
Message string
}
func testCodec(t *testing.T, codec DataCodec) {
var (
d = SimpleData{
ID: 1234,
Message: "Hello",
}
)
m, err := codec.Encode(&d)
assert.NoError(t, err, "encode error")
log.Info(m)
d2, err := codec.Decode(m)
assert.NoError(t, err, "decode error")
assert.Equal(t, *d2.(*SimpleData), d)
}
func benchmarkCodec(b *testing.B, codec DataCodec) {
var (
d = SimpleData{
ID: 1234,
Message: "Hello",
}
)
for i := 0; i < b.N; i++ {
d.ID = i
m, _ := codec.Encode(&d)
codec.Decode(m)
}
}
func TestStructCodec(t *testing.T) {
testCodec(t, StructCodec(&SimpleData{}))
}
func BenchmarkStructCodec(b *testing.B) {
benchmarkCodec(b, StructCodec(SimpleData{}))
}
func TestJsonCodec(t *testing.T) {
testCodec(t, JsonCodec(SimpleData{}))
}
func BenchmarkJsonCodec(b *testing.B) {
benchmarkCodec(b, JsonCodec(SimpleData{}))
}
func TestMsgpackCodec(t *testing.T) {
testCodec(t, MsgpackCodec(SimpleData{}))
}
func BenchmarkMsgpackCodec(b *testing.B) {
benchmarkCodec(b, MsgpackCodec(SimpleData{}))
}
type customizeCodec struct {
}
func (c customizeCodec) Encode(d interface{}) (map[string]interface{}, error) {
d2 := d.(*SimpleData)
return map[string]interface{}{
"ID": strconv.Itoa(d2.ID),
"Message": d2.Message,
}, nil
}
func (c customizeCodec) Decode(v map[string]interface{}) (interface{}, error) {
id, _ := strconv.Atoi(v["ID"].(string))
return &SimpleData{
ID: id,
Message: v["Message"].(string),
}, nil
}
var CustomizeCodec customizeCodec
func TestCustomizeCodec(t *testing.T) {
testCodec(t, CustomizeCodec)
}
func BenchmarkCustimizeCodec(b *testing.B) {
benchmarkCodec(b, CustomizeCodec)
}