-
Notifications
You must be signed in to change notification settings - Fork 211
/
codec_test.go
77 lines (55 loc) · 1.39 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
package noise
import (
"encoding/binary"
"github.com/stretchr/testify/assert"
"testing"
)
type test2 struct {
data []byte
}
func (t test2) Marshal() []byte {
return t.data
}
func unmarshalTest2(data []byte) (test2, error) {
return test2{data: data}, nil
}
type test struct {
data []byte
}
func (t test) Marshal() []byte {
return t.data
}
func unmarshalTest(data []byte) (test, error) {
return test{data: data}, nil
}
func TestCodecRegisterEncodeDecode(t *testing.T) {
t.Parallel()
codec := newCodec()
opcode := codec.register(test{}, unmarshalTest)
msg := test{data: []byte("hello world")}
expected := make([]byte, 2+len(msg.data))
binary.BigEndian.PutUint16(expected[:2], opcode)
copy(expected[2:], msg.data)
data, err := codec.encode(msg)
assert.NoError(t, err)
assert.EqualValues(t, opcode, binary.BigEndian.Uint16(data[:2]))
assert.EqualValues(t, expected, data)
obj, err := codec.decode(data)
assert.NoError(t, err)
assert.IsType(t, obj, test{})
// Failure cases.
data[0] = 99
_, err = codec.decode(data)
assert.Error(t, err)
_, err = codec.encode(test2{data: []byte("should not be encodable")})
assert.Error(t, err)
}
func TestPanicIfDuplicateMessagesRegistered(t *testing.T) {
t.Parallel()
codec := newCodec()
assert.Panics(t, func() {
codec.register(test{}, unmarshalTest)
codec.register(test2{}, unmarshalTest2)
codec.register(test{}, unmarshalTest)
})
}