forked from zssky/zk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
structs_test.go
84 lines (77 loc) · 2.28 KB
/
structs_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
package zk
import (
"reflect"
"testing"
)
func TestEncodeDecodePacket(t *testing.T) {
t.Parallel()
encodeDecodeTest(t, &requestHeader{-2, 5})
encodeDecodeTest(t, &connectResponse{1, 2, 3, nil})
encodeDecodeTest(t, &connectResponse{1, 2, 3, []byte{4, 5, 6}})
encodeDecodeTest(t, &getAclResponse{[]ACL{{12, "s", "anyone"}}, Stat{}})
encodeDecodeTest(t, &getChildrenResponse{[]string{"foo", "bar"}})
encodeDecodeTest(t, &pathWatchRequest{"path", true})
encodeDecodeTest(t, &pathWatchRequest{"path", false})
encodeDecodeTest(t, &CheckVersionRequest{"/", -1})
encodeDecodeTest(t, &reconfigRequest{nil, nil, nil, -1})
encodeDecodeTest(t, &multiRequest{Ops: []multiRequestOp{{multiHeader{opCheck, false, -1}, &CheckVersionRequest{"/", -1}}}})
}
func TestRequestStructForOp(t *testing.T) {
for op, name := range opNames {
if op != opNotify && op != opWatcherEvent {
if s := requestStructForOp(op); s == nil {
t.Errorf("No struct for op %s", name)
}
}
}
}
func encodeDecodeTest(t *testing.T, r interface{}) {
buf := make([]byte, 1024)
n, err := encodePacket(buf, r)
if err != nil {
t.Errorf("encodePacket returned non-nil error %+v\n", err)
return
}
t.Logf("%+v %x", r, buf[:n])
r2 := reflect.New(reflect.ValueOf(r).Elem().Type()).Interface()
n2, err := decodePacket(buf[:n], r2)
if err != nil {
t.Errorf("decodePacket returned non-nil error %+v\n", err)
return
}
if n != n2 {
t.Errorf("sizes don't match: %d != %d", n, n2)
return
}
if !reflect.DeepEqual(r, r2) {
t.Errorf("results don't match: %+v != %+v", r, r2)
return
}
}
func TestEncodeShortBuffer(t *testing.T) {
t.Parallel()
_, err := encodePacket([]byte{}, &requestHeader{1, 2})
if err != ErrShortBuffer {
t.Errorf("encodePacket should return ErrShortBuffer on a short buffer instead of '%+v'", err)
return
}
}
func TestDecodeShortBuffer(t *testing.T) {
t.Parallel()
_, err := decodePacket([]byte{}, &responseHeader{})
if err != ErrShortBuffer {
t.Errorf("decodePacket should return ErrShortBuffer on a short buffer instead of '%+v'", err)
return
}
}
func BenchmarkEncode(b *testing.B) {
buf := make([]byte, 4096)
st := &connectRequest{Passwd: []byte("1234567890")}
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
if _, err := encodePacket(buf, st); err != nil {
b.Fatal(err)
}
}
}